0

I want to make a different change on all elements who are sharing the same class, however, i can't use queryselectorAll as insertAdjacentHTML do not support queryselectorAll. How can i do that?

var description = document.querySelector("h1.plp__title");

function showDescription (){
    if(description.textContent = "shoes"){
        description.insertAdjacentHTML('afterend','<p>Hello World</p>');
    }else if(cdescription.textContent = "Bags"){
        description.insertAdjacentHTML('afterend','<p>Hello World2</p>');
    } else {
        return;
    }
};
Snirka
  • 602
  • 1
  • 5
  • 19
  • 2
    what exactly do you mean by *insertAdjacentHTML do not support queryselectorAll*? – DecPK Jun 30 '21 at 08:57
  • 1
    `queryselectorAll` returns an array-like container of elements. You have to iterate over it and call this function for each element. –  Jun 30 '21 at 08:58
  • it will show TypeError: description.insertAdjacentHTML is not a function if i use queryselectorAll – Charmaine Ho Jun 30 '21 at 08:58
  • `document.querySelectorAll(...).forEach(el => el.insertAdjacentHTML(....));` – Yousaf Jun 30 '21 at 08:59
  • You can't use Node properties against a NodeList. You're expecting jQuery functionality in vanilla JS. You can iterate the NodeList and then use insertAdjacentHTML on each Node. – Riddell Jun 30 '21 at 08:59
  • 1
    `=` is assignment not comparison. Use `===` instead. Then use querySelectorAll and loop over the results . – Mihai T Jun 30 '21 at 09:03

2 Answers2

1

queryselectorAll returns an array-like container (NodeList) of elements. You have to iterate over it and call this function for each element.

var descriptions = document.querySelectorAll("h1.plp__title");

function showDescription() {
  descriptions.forEach(description => {
    if (description.textContent === "shoes") {
      description.insertAdjacentHTML('afterend', '<p>Hello World</p>');
    } else if (description.textContent === "Bags") {
      description.insertAdjacentHTML('afterend', '<p>Hello World2</p>');
    } else {
      return;
    }
  });
}

showDescription();
<h1 class="plp__title">shoes</h1>
<h1 class="plp__title">Bags</h1>

description.textContent = "shoes" and description.textContent = "Bags" are assignments, not comparisons.

1

querySelectorAll returns a nodeList. You will have to iterate through that list, and use insertAdjacentHTML within the iteration.

zkriszti
  • 37
  • 1
  • 5