Home > Back-end >  insertAdjacentElement adds only one element, when insertAdjacentHTML adds four
insertAdjacentElement adds only one element, when insertAdjacentHTML adds four

Time:12-22

So i wanted my webpage to create one dot button for every photo that was placed by me in a slides NodeList. Instead, it just creates just one dot, just like if there was just one image, but there are 4 images actually.

const dotContainer = document.querySelector('.dots');
const slides = document.querySelectorAll('.slide');
const slider = document.querySelector('.slider');
// images are name slides!

const createDots = function () {
  const dot = document.createElement('button');
  dot.classList.add('dots__dot');
  slides.forEach((s, i) => {
    dotContainer.insertAdjacentElement('beforeend', dot);

  });
  const dots = document.querySelectorAll('.dots__dot');
  dots.forEach((d, i) => (d.dataset.slide = `${i}`));
};

createDots();


    console.log(s); // NodeList(4) [div.slide, div.slide, div.slide, div.slide]

HTML view after using insertAdjacentElement

But when i used insertAdjacentHTML... it worked!



const createDots = function () {
  const dot = document.createElement('button');
  dot.classList.add('dots__dot');
  slides.forEach((s, i) => {
    // dotContainer.insertAdjacentElement('beforeend', dot);
    dotContainer.insertAdjacentHTML(
      'beforeend',
      `<button  data-slide="0"></button>`
    );
  });
  const dots = document.querySelectorAll('.dots__dot');
  dots.forEach((d, i) => (d.dataset.slide = `${i}`));
};
createDots();

HTML view after using insertAdjacentHTML

Why?

CodePudding user response:

You're trying to add the same element several times. You need to create a new element at every foreach callback before inserting it

  • Related