Home > OS >  Create div & and then div inside of it
Create div & and then div inside of it

Time:08-03

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

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

Any help?

CodePudding user response:

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>

  • Related