简体   繁体   中英

Looping through NodeList Removes Element

I have a simple script where I want to change "br" to ", br by" in a NodeList. The code is:

const captions = document.querySelectorAll('.ae-overlay-caption');
const br = document.createElement("br");
for (i = 0; i < captions.length; i++) {
    captions[i].firstElementChild.replaceWith(",", br, " by");
    };

When I check the NodeList before running this script, each node has a "br" for firstElementChild. After running the script, the br's for the first x nodes are removed, and only the last node is updated. You can see the problem here: https://editart2020.crooked.media/collection/fundamentos/ . Mouse over the images. Only the last one works.

What am I doing wrong?

Your replaceWith adds the same element in each loop iteration.

As a DOM element can only be present at one location in the DOM, in the n-th iteration it will remove the element from the (n-1)th caption and add it to the n-th caption. Therefore, at the end of the loop, only the last caption will contain the element.

Move the createElement inside the loop, to generate one element per interation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM