Could someone please clarify why I am unable to declare the var
node before the for loop and then simply use appendChild(node)
inside the loop? Why is it necessary to declare it for each iteration in order for it to affect all div elements? Otherwise, it would just append the textWebinare
to the last element. The Variable remains unchanged within my loop and I'm struggling to understand this concept.
NOT FUNCTIONAL:
<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>
WORKS:
<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>