Reputation: 318
This may be a more basic question as I am learning/practicing using the DOM. But I have the following:
var demo_div = document.createElement("div")
demo_div.classList.add("demo")
var p_div = document.createElement("p")
var br = document.createElement("br")
for(let i = 0; i < 100; i++){
if (i % 5 == 0){
var text = document.createTextNode("meow")
}
else{
var text = document.createTextNode("woof")
}
p_div.appendChild(text)
p_div.appendChild(br)
}
demo_div.appendChild(p_div)
document.body.appendChild(demo_div)
I'm trying to create a div with the class = "demo" and then append a child node which is a paragraph to it. The paragraph will have 100 lines but every 5th line will have a different value.
That part wasn't hard at all the part I'm confused about is when I append the break to the paragraph, after each line is appended, the break doesn't actually work. Instead the break shows up at the end of the loop (As seen in the inspector). Any insight would be appreciated. Thanks.
Upvotes: 2
Views: 178
Reputation: 30360
You need to create a unique <br>
element for each line break that you
want applied. Currently you're reusing the same <br>
element which causes that same element to shift from it's last position to the next point in the text that you place it (via appendChild()
).
Consider adding var br = document.createElement("br")
inside your loop construct as shown:
var demo_div = document.createElement("div")
demo_div.classList.add("demo")
var p_div = document.createElement("p")
for(let i = 0; i < 100; i++){
if (i % 5 == 0){
var text = document.createTextNode("meow")
}
else{
var text = document.createTextNode("woof")
}
// Create a new br element for each loop iteration, and append it
// to your div like so:
var br = document.createElement("br")
p_div.appendChild(text)
p_div.appendChild(br)
}
demo_div.appendChild(p_div)
document.body.appendChild(demo_div)
Upvotes: 1
Reputation: 370759
You're only every creating one br
- see how its creation is outside of the loop, rather than inside of the loop. When you call appendChild
with an element that already exists in the DOM, the element is removed from its previous location and appended to the new parent.
Create the <br>
inside the loop instead, just like you're doing with text
:
var demo_div = document.createElement("div")
demo_div.classList.add("demo")
var p_div = document.createElement("p")
for(let i = 0; i < 100; i++){
var br = document.createElement("br")
if (i % 5 == 0){
var text = document.createTextNode("meow")
}
else{
var text = document.createTextNode("woof")
}
p_div.appendChild(text)
p_div.appendChild(br)
}
demo_div.appendChild(p_div)
document.body.appendChild(demo_div)
Upvotes: 0