Reputation: 29
I am trying to create something like this using only DOM:
<div class="parent">
<p><div id="child1">My First Child</div></p>
<div id="child2"><p>Second Child Node</p></div>
</div>
And I have only manage to create each individual element like so:
let div1 = document.createElement("div");
div1.setAttribute("class", "parent");
let div2 = document.createElement("div");
div2.setAttribute("id", "child1");
div2.textContent = "My First Child";
let div3 = document.createElement("div");
div3.setAttribute("id", "child2");
div3.textContent = "Second Child Node";
My question here is: Can I combine everything into one so I only have to use document.appendChild(div1)
or does the nesting process needs to be done during the append process.
Upvotes: 1
Views: 853
Reputation: 25408
body
contain single child i.e div
with class parent
stored in parentDiv
.
parentDiv
contain 2 child i.e p
and div
with id child2
p
container single child i.e div
with id child1
div
with id child2
contain single p
body
= (p
) + (div
) where
p
contains div
with id child1
div
with id child2
contains p
const parentDiv = document.createElement("div")
parentDiv.classList.add("parent");
const p1 = document.createElement("p");
const divChild1 = document.createElement("div");
divChild1.setAttribute("id", "child1");
divChild1.textContent = "My First Child";
p1.appendChild(divChild1);
const divChild2 = document.createElement("div");
divChild2.setAttribute("id", "child2");
const p2 = document.createElement("p");
p2.textContent = "Second Child Node";
divChild2.appendChild(p2);
parentDiv.appendChild(p1);
parentDiv.appendChild(divChild2);
document.body.appendChild(parentDiv)
Upvotes: 1
Reputation: 3411
You can do it by insertAdjacentHTML:
document
.querySelector(".parent-of-parent")
.insertAdjacentHTML('afterbegin', `
<div class="parent">
<p><div id="child1">My First Child</div></p>
<div id="child2"><p>Second Child Node</p></div>
</div>`
);
<div class="parent-of-parent"></div>
Upvotes: 2