-1

It works very well when capturing IDs But the problem is that it cannot fetch more than one data. Thats why i want to use querySelectorAll() method.

const titleHoverImageUrl = document.getElementById("toggle").getAttribute("data-image");
console.log(titleHoverImageUrl);

But when i'm holding the class name why it's not working and how can i solve it please kindly tell me.

const titleHoverImageUrl2 = document.querySelectorAll(".toggle").getAttribute("data-image");
console.log(titleHoverImageUrl2);

I want to use many custom attribute values but I can't figure out how to do it Kindly tell me.

  • you get a list with query selector all – This Guy Aug 04 '23 at 13:29
  • 1
    The two pieces of code are not equivalent. `getElementById` returns one element, `querySelectorAll` returns an array-like object called [`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList). – evolutionxbox Aug 04 '23 at 13:29
  • 1
    MDN is the GO TO resource for web documentation! https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll – This Guy Aug 04 '23 at 13:31
  • `document.querySelector(".toggle").dataset.image` for the first toggle element's data-image attribute. To show all: `document.querySelectorAll(".toggle").forEach(toggle => console.log(toggle.dataset.image));` console.log(titleHoverImageUrl2);` – mplungjan Aug 04 '23 at 13:35

0 Answers0