[英]Javascript How can I get the href from no id anchor tag?
<a href="href">inner</a>
下面的函数不起作用,因为没有 id:
document.getElementById("???").href
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.这会将所有
a
元素存储到一个数组中。 If you know exactly which element you want, extract it from the array based on its order in the page and grab the href
:如果你确切地知道你想要哪个元素,根据它在页面中的顺序从数组中提取它并获取
href
:
var href = anchor[1].href;
Example jsfiddle (watch for the alert
)示例jsfiddle (注意
alert
)
您可以使用document.querySelector('a[href="href"]')
并通过属性值获取元素。
You could use getElemntsByTagName.您可以使用 getElemntsByTagName。 It's probably better just to add in an id attribute though...
不过,最好只添加一个 id 属性......
document.getElementsByTagName("a");
As everyone suggested getElementsByTagName
is the right way to go if the element doesn't have an id or a class.正如每个人都建议的那样,如果元素没有 id 或类,
getElementsByTagName
是正确的方法。 But thats going to give you a NodeList
of all the anchor links you have on your DOM.但这会给你一个你在你的 DOM 上拥有的所有锚链接的
NodeList
。
So, if you can add an id or class to the anchor link, that's your best option.因此,如果您可以向锚链接添加 id 或类,那是您的最佳选择。 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/class 的 div 包裹你的锚链接(假设 id 是
unique-wrapper
)并使用它。
document.getElementById('unique-wrapper').getElementsByTagName('a')
See jsFiddle Demo参见jsFiddle 演示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.