I'm trying to make a javascript module to replace all occurrences of html elements that has the class .item2. but my code below only replaces the last occurrence and erases the other occurrences. what am I doing wrong?
// before replacement
/*
first one;first two;first three;
second one;second two;second three;
another one;another two;another three;
*/
// expected result
/*
first one;Hellofirst three;
second one;Hellosecond three;
another one;Helloanother three;
*/
// what I currently get
/*
first one;first three;
second one;second three;
another one;Helloanother three;
*/
const c1 = document.querySelector('#container1');
const c2 = document.querySelector('#container2');
const c3 = document.querySelector('#container3');
let str = '<span class="item1">first one;</span>';
c1.insertAdjacentHTML('beforeend', str);
str = '<span class="item2">first two;</span>';
c1.insertAdjacentHTML('beforeend', str);
str = '<span class="item3">first three;</span>';
c1.insertAdjacentHTML('beforeend', str);
str = '<span class="item1">second one;</span>';
c2.insertAdjacentHTML('beforeend', str);
str = '<span class="item2">second two;</span>';
c2.insertAdjacentHTML('beforeend', str);
str = '<span class="item3">second three;</span>';
c2.insertAdjacentHTML('beforeend', str);
str = '<span class="item1">another one;</span>';
c3.insertAdjacentHTML('beforeend', str);
str = '<span class="item2">another two;</span>';
c3.insertAdjacentHTML('beforeend', str);
str = '<span class="item3">another three;</span>';
c3.insertAdjacentHTML('beforeend', str);
let elems = document.querySelectorAll('.item2');
console.log('all children', elems);
str = '<span data-rpl="item2" class="new">Hello</span>';
let newElem = makeElem(str);
elems.forEach((item, key) => {
console.log('each', key, item);
item.replaceWith(newElem);
});
function makeElem(str) {
const template = document.createElement('template');
template.innerHTML = str;
return template.content.firstChild;
}
<div id="container1"></div>
<div id="container2"></div>
<div id="container3"></div>
newElem) multiple times, and since a single element can only exist in one place in the DOM, it is being left at the last place it was inserted. You should be able to move thelet newElem = ...inside the loop to avoid this.