Rawnly Rawnly - 3 years ago 691
HTML Question

JavaScript: getElementsByTagName()

i need to select all items with

tag in my page and add them a class with classList i've tried with
and the
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 () {

Thanks in advance.

Answer Source

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 () {

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download