开发者

Beginner Javascript error with getAttribute

I've searched quite a bit on both google and stackoverflow, but a lack of knowledge on how to ask the q开发者_运维问答uestion (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.


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;
}


Calling nav.getElementsByTagName('a') returns list of objects. And that list doesn't have getAttribute() method. You must call it on ONE object.

When you do:

navLinks[0].getAttribute('title')

then it should work - you will get title of the first matched element.


var navLinks = nav.getElementsByTagName('a');

getElementsByTagName returns multiple elements (hence Elements), because there can be multiple elements on one page with the same tag name. A NodeList (which is a collection of nodes as returned by getElementsByTagName) does not have a getAttribute method.

You need to access the property of the element that you actually need. My guess is that this will be the first element you find.

var title = navLinks[0].getAttribute('title');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜