Beginner Javascript error with getAttribute

Squadrons picture Squadrons · Jul 17, 2011 · Viewed 7.4k times · Source

I've searched quite a bit on both google and stackoverflow, but a lack of knowledge on how to ask the question (or even if I'm asking the right question at all) is making it hard to find pertinent information.

I have a simple block of code that I am experimenting with to teach myself javascript.

var studio = document.getElementById('studio');
var contact = document.getElementById('contact');
var nav = document.getElementById('nav');
var navLinks = nav.getElementsByTagName('a');

var title = navLinks.getAttribute('title');

I want to grab the title attribute from the links in the element with the ID 'nav'.

Whenever I look at the debugger, it tells me that Object #<NodeList> has no method 'getAttribute'

I have no idea where I'm going wrong.

The nodetype and nodevalue for navLinks comes back as undefined, which I believe may be part of the problem, but I'm so new to this that I honestly have no idea.

Answer

Darin Dimitrov picture Darin Dimitrov · Jul 17, 2011

The getElementsByTagName method returns an array of objects. So you need to loop through this array in order to get individual elements and their attributes:

var navLinks = nav.getElementsByTagName('a');
for (var i = 0; i < navLinks.length; i++) {
    var link = navLinks[i];
    var title = link.title;
}