Rawnly Rawnly - 6 months ago 32
HTML Question

JavaScript: getElementsByTagName()

i need to select all items with

<a></a>
tag in my page and add them a class with classList i've tried with
getElementsByTagName('A')
and the
document.querySelectorAll('a')
but it doesn't works... here i found an example of W3schools but is the same it doesn't work, so what i can do? (I am on Safari)

Here the code

var link = document.querySelector( 'a' );

link.onmouseover = function () {
link.classList.toggle("tada");
};


Thanks in advance.

Answer

The getElementsByTagName('a') and querySelectorAll('a') functions should work as expected returning either an HTMLCollection or a NodeList respectively, both of which will require you to iterate through to actually set up your event handler :

// Get your links
var links = document.getElementsByTagName('a');
// Iterate through them and set up your event handlers
for(var l = 0; l < links.length; l++){
      links[l].onmouseover = function () {
         this.classList.toggle("tadan");
      };
}

It's also important to note that getElementsByTagName() will return a "live" HTMLCollection of elements, whereas querySelectorAll() will return a "non-live" NodeList, which can affect how the elements in these are used.