Home > Back-end >  selecting all elements and adding new element after each one
selecting all elements and adding new element after each one

Time:01-29

I have some simple vanilla code here. My goal is to grab all the sections, loop through them and after each one insert a new element:

let sectionSign = document.createElement('p');
sectionSign.innerHTML = '§'
sectionSign.style.marginTop = '1rem'

let allSections = document.querySelectorAll('section')

allSections.forEach((section) => {
    section.style.border = '1px solid red'
    section.after(sectionSign)
})

the style.border was just to make sure it selected all the elements that I wanted and it did. However, the sectionSign is only being added after the last section, not after each one. How can I resolve this?

CodePudding user response:

Try this instead, you have to create a new element for each section.

let allSections = document.querySelectorAll('section')

allSections.forEach((section) => {
    let sectionSign = document.createElement('p');
    sectionSign.innerHTML = '§';
    sectionSign.style.marginTop = '1rem';
    section.style.border = '1px solid red';
    section.after(sectionSign);
});
  •  Tags:  
  • Related