Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create div & and then div inside of it

I can create a new div with the following syntax:

function createClass() {
 const firstDiv = document.createElement('div')
 firstDiv.classList.add('class1')
 container.appendChild(firstDiv)
}

Next I want to create a new div inside of that div. I tried the same syntax without success:

function createClass() {
 const firstDiv = document.createElement('div')
 firstDiv.classList.add('class1')
 container.appendChild(firstDiv)

 const secondDiv = document.createElement('div')
 secondDiv.classList.add('class2')
 firstDiv.appendChild(secondDiv)
}

If I use the following syntax it works, but there is a problem. If the function is executed more than once, it only creates second class once. So if executed twice, the result would be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div class="class1"><div class="class2"></div></div>
<div class="class1"></div></div>

document.getElementsByClassName('class1')[0].appendChild(secondDiv)

Any help?

>Solution :

Your code doesn’t include appending the dynamic HTML to the document. But when that’s done, the output is as expected.

let container = document.getElementById("container");

function createClass() {
 const firstDiv = document.createElement('div')
 firstDiv.classList.add('class1')
 container.appendChild(firstDiv)

 const secondDiv = document.createElement('div')
 secondDiv.classList.add('class2')
 firstDiv.appendChild(secondDiv)
 
 // Your post doesn't include appending the first div to the document
 container.appendChild(firstDiv);
}

createClass();
createClass();
console.log(container.innerHTML);
<div id="container"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading