Search code examples
javascripthtmlclassappendappendchild

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:

<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>