I am trying to duplicate the content of the Html element .slideTrack by getting it from querySelectorAll and append the nodelist with a spread operator.
I think that a nodelist can't be append() directly to an element with the spread operator so in the documentation of Nodelist I tried to use the NodeList.item() that is returning a Node that I should pass to the append() method. I made a simple for loop but it is not working either. I don't understand why it is not working, any help ?
const allSlides = document.querySelectorAll(".citation");
const slideTrack = document.querySelector(".slideTrack");
//first trying directly with the spread operator
slideTrack.append(...allSlides);
//then trying with the item() method and a simple for loop
for (i=0;i<allSlides.length;i++) {
slideTrack.append(allSlides.item(i));
}
<div class="slideTrack">
<div class="citation">
<p class="text">test1</p>
</div>
<div class="citation">
<p class="text">test2</p>
</div>
<div class="citation">
<p class="text">test3</p>
</div>
<div class="citation">
<p class="text">test4</p>
</div>
<div class="citation">
<p class="text">test5</p>
</div>
</div>
append()
appends the node to the new location, which removes it from the old location. It doesn't make a copy of the node.
If you want to leave the node in the old location, use .cloneNode(true)
to make a copy of the node and its descendants.
const allSlides = document.querySelectorAll(".citation");
const slideTrack = document.querySelector(".slideTrack");
//then trying with the item() method and a simple for loop
for (i=0;i<allSlides.length;i++) {
slideTrack.append(allSlides[i].cloneNode(true));
}
<div class="slideTrack">
<div class="citation">
<p class="text">test1</p>
</div>
<div class="citation">
<p class="text">test2</p>
</div>
<div class="citation">
<p class="text">test3</p>
</div>
<div class="citation">
<p class="text">test4</p>
</div>
<div class="citation">
<p class="text">test5</p>
</div>
</div>