Appending div in div doesn't work as expected

I have got the following HTML

    <div id="container">
        <div id="myDiv"></div>
    </div>

I am wondering why when running this code

<script>
        $("#myDiv").append("<div class='row'>");
        $("#myDiv").append("<span>abc</span");
        $("#myDiv").append("</div>");
</script>

I am getting this

<div id="container">
        <div id="myDiv">
               <div class="row"></div>
               <span>abc</span>
         </div>
</div>

And not, what I was hoping, this:

<div id="container">
        <div id="myDiv">
			<div class="row">
				<span>abc</span>
			</div>
		</div>
</div>

See https://codepen.io/Corobori/pen/ZEyzJoZ

Hi, It looks like you should be appending your span to .row rather than #myDiv

Try it like this…

$("#myDiv").append("<div class='row'>");
$(".row").append("<span>abc</span>");
$("#myDiv").append("</div>");
2 Likes

Here’s how you could do it in Vanilla JavaSript

myDiv = document.querySelector('#myDiv');
myClassRow = document.createElement('div');

mySpan = document.createElement('span');

myDiv.appendChild(myClassRow);
myClassRow.classList.add('row');
myClassRow.appendChild(mySpan);

mySpan.textContent = "ABC";

However, it plays funny using jQuery and Bootstrap (?), but that might just be CodePen

https://codepen.io/Strider64/pen/jOwNxQe

Though doing it in JQuery takes less code in JavaScript and is a little easier to read.

Thank you, but I have to do it Jquery, the code I posted was actually a simulation of a more complex code.

Thank you for your code

The final version will be as shown below

$("#myDiv").append("<div class='row'>");
$(".row").append("<div class='col-lg-12'><span>abc</span></div>");
$("#myDiv").append("</div>");

Couldn’t you just use one append to save three trips to the page?

e.g.

var myhtml = "<div class='row'>" + "<span>abc</span></div>"
$("#myDiv").append(myhtml);
2 Likes

Sure can ! Thank you.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.