getAttribute 的初学者 Javascript 错误
我在 google 和 stackoverflow 上进行了相当多的搜索,但由于缺乏如何提出问题的知识(或者即使我问的是正确的问题),所以很难找到相关信息。
我有一个简单的代码块,我正在尝试用它来自学 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');
我想从 ID 为“nav”的元素中的链接中获取标题属性。
每当我查看调试器时,它都会告诉我 Object #
我不知道哪里出了问题。
navLinks 的节点类型和节点值返回为未定义,我认为这可能是问题的一部分,但我对此很陌生,老实说我不知道。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
getElementsByTagName
方法返回一个对象数组。因此,您需要循环遍历该数组才能获取各个元素及其属性: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:调用
nav.getElementsByTagName('a')
返回对象列表。并且该列表没有 getAttribute() 方法。您必须在一个对象上调用它。当你这样做时:
那么它应该可以工作 - 你将获得第一个匹配元素的标题。
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:
then it should work - you will get title of the first matched element.
getElementsByTagName
返回多个元素(因此是Elements
),因为一页上可以有多个具有相同标记名称的元素。NodeList
(它是getElementsByTagName
返回的节点集合)没有getAttribute
方法。您需要访问实际需要的元素的属性。我的猜测是,这将是您找到的第一个元素。
getElementsByTagName
returns multiple elements (henceElements
), because there can be multiple elements on one page with the same tag name. ANodeList
(which is a collection of nodes as returned bygetElementsByTagName
) does not have agetAttribute
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.