-4

Can i add an animation to all the links in the page?

Here the code

  var words = document.links;

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

Thanks in advance.

Federico
  • 380
  • 3
  • 15

2 Answers2

2

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.

Rion Williams
  • 74,820
  • 37
  • 200
  • 327
  • https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName seems to indicate that getElementsByTagName returns an HTMLCollection. Is the only difference between an HTMLCollection and a NodeList that the HTMLCollection is always live? – heapunderflow May 11 '16 at 15:05
  • You are correct. For some reason I suppose I was referencing the wrong function initially. But yes, the `HTMLCollection` is live and the `NodeList` is not. – Rion Williams May 11 '16 at 15:06
0

gotta loooopp

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

for(var i=link.length; i--;)
    link[i].onmouseover = function () {
          this.classList.toggle("tadan");
    };

OR you do have jQuery tagged so you could just

$('a').mouseover(function(){
    $(this).toggleClass('tadan');
});
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116