1

Trying to create an event to fire once a footer link has been clicked.

var hooray = function(event) {
  console.log("hooray");
};

var footer_link = document.getElementsByClassName('footer-link');
console.log(footer_link);
footer_link.addEventListener('click', hooray, false);
<li class="footer-link">Title link
  <ul class="footer-link-sub">
    <li><a href="">link</a></li>
    <li><a href="">link</a></li>
    <li><a href="">link</a></li>
    <li><a href="">link</a></li>
  </ul>
</li>

I get an error of "Uncaught TypeError: footer_link.addEventListener is not a function". If the eventListener is taken out the console will log the correct li from the markup. Or if the element selector is removed from addEventListener it will fire whenever the page is clicked as expected. What am I doing wrong to select the element?

Mark
  • 11
  • 1
  • 1
    See http://stackoverflow.com/questions/10693845/what-does-getelementsbyclassname-return. –  Jul 12 '15 at 19:47

2 Answers2

1

getElementsByClassName returns a NodeList - that is, a list containing more than one element.

If you only want the first one, you need to access it by [0]. That is, accessing it by indexer. NodeLists are indexed (like arrays) so [0] returns the first element, [1] returns the second element and so on - there is only one element in your case.

var hooray = function(event) {
  alert("hooray");
};

var footer_link = document.getElementsByClassName('footer-link');
console.log(footer_link);
// Note the [0] here
footer_link[0].addEventListener('click', hooray, false);
<li class="footer-link">Title link
  <ul class="footer-link-sub">
    <li><a href="">link</a></li>
    <li><a href="">link</a></li>
    <li><a href="">link</a></li>
    <li><a href="">link</a></li>
  </ul>
</li>
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
0

That is because 'getElementByClassName' returns an array, so you need to select the first element of the array. Try using footer_link[0]

var hooray = function(event) {
  console.log("hooray");
};

var footer_link = document.getElementsByClassName('footer-link');
console.log(footer_link);
footer_link[0].addEventListener('click', hooray, false);
<li class="footer-link">Title link
  <ul class="footer-link-sub">
    <li><a href="">link</a></li>
    <li><a href="">link</a></li>
    <li><a href="">link</a></li>
    <li><a href="">link</a></li>
  </ul>
</li>
Ankur Anand
  • 535
  • 2
  • 9