简体   繁体   中英

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM