Javascript 如何从无 id 锚标记中获取 href?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18873748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript How can I get the href from no id anchor tag?
提问by user2791659
<a href="href">inner</a>
Function below doesn't work because there's no id:
下面的函数不起作用,因为没有 id:
document.getElementById("???").href
回答by Brian Phillips
You can use getElementsByTagName
to find the a
elements:
您可以使用getElementsByTagName
来查找a
元素:
var anchor = document.getElementsByTagName("a");
This will store all a
elements into an array. If you know exactly which element you want, extract it from the array based on its order in the page and grab the href
:
这会将所有a
元素存储到一个数组中。如果你确切地知道你想要哪个元素,根据它在页面中的顺序从数组中提取它并获取href
:
var href = anchor[1].href;
Example jsfiddle(watch for the alert
)
示例jsfiddle(注意alert
)
回答by Joel Murphy
You could use getElemntsByTagName. It's probably better just to add in an id attribute though...
您可以使用 getElemntsByTagName。不过,最好只添加一个 id 属性......
document.getElementsByTagName("a");
回答by Krishna
As everyone suggested getElementsByTagName
is the right way to go if the element doesn't have an id or a class. But thats going to give you a NodeList
of all the anchor links you have on your DOM.
正如每个人所建议getElementsByTagName
的,如果元素没有 id 或类,这是正确的方法。但这会给你一个NodeList
你在你的 DOM 上拥有的所有锚链接。
So, if you can add an id or class to the anchor link, that's your best option. If that's not an option, see if you can wrap your anchor link with a div with a unique id/class (lets say id is unique-wrapper
) & use this.
因此,如果您可以向锚链接添加 id 或类,那是您的最佳选择。如果这不是一个选项,看看你是否可以用一个具有唯一 id/class 的 div 包裹你的锚链接(假设 id is unique-wrapper
)并使用它。
document.getElementById('unique-wrapper').getElementsByTagName('a')
See jsFiddle Demo