Reputation: 57
Can someone explain me why I cant declare the var
node before the for loop? And then just appendChild(node)
inside the loop? Why do I have to declare it for every iteration, for it to have effect on all div elements? Else it would just add the textWebinare
to the last element. The Variable is not changed inside my loop so I can't really wrap my head around it.
DOES NOT WORK:
<div class="video-container">
test
</div>
<div class="video-container">
test
</div>
<div class="video-container">
test
</div>
<script>
document.addEventListener("DOMContentLoaded", function() {
var node = document.createElement('div');
node.setAttribute("id", "textWebinare");
var video = document.getElementsByClassName("video-container");
var i;
for(i = 0; i<video.length; i++){
video[i].appendChild(node);
}
});
</script>
DOES WORK:
<div class="video-container">
test
</div>
<div class="video-container">
test
</div>
<div class="video-container">
test
</div>
<script>
document.addEventListener("DOMContentLoaded", function() {
var video = document.getElementsByClassName("video-container");
var i;
for(i = 0; i<video.length; i++){
var node = document.createElement('div');
node.setAttribute("id", "textWebinare");
video[i].appendChild(node);
}
});
</script>
Upvotes: 0
Views: 136
Reputation: 943547
Consider document.createElement('div')
to be like creating a car.
Then consider video[i]
to be a parking space and appendChild(node)
to be parking a car in that space.
If you create one car, and then park it in a three of parking spaces in sequence then you'll end up with one car in the last space, not a car in each of three spaces.
If you want a car in each space then you'll need to create three cars.
A single div can't be in multiple parts of the same HTML document at the same time.
Upvotes: 3