Home > Back-end >  Trying to access and manipulate a HTML Collection
Trying to access and manipulate a HTML Collection

Time:03-25

Hello everybody,

I am trying to access and manipulate a HTML collection using these methods enter image description here

CodePudding user response:

Instead of using getElementByTagName, you can use querySelectorAll("article"). The reason getElementByTagName doesn't work is because document is not considered an Element, as per the documentation suggests you need. However, it is considered a parentNode (which is why querySelectorAll will work.

If you want to use getElementByTagName try doing document.querySelector("body").getElementByTagName("article"), but in this case, its better to do document.querySelectorAll("article")

CodePudding user response:

You likely execute the script before the elements exist.

Try

window.addEventListener("DOMContentLoaded", () => {
  console.log(document.querySelectorAll("article").length);
})
  • Related