【发布时间】:2026-01-23 03:00:01
【问题描述】:
我有这个功能,它假设从页面中获取所有 a 标签,我正在尝试这些链接中的所有锚点,但我不断收到 Object [object HTMLAnchorElement] has no method errors, 我试过使用 split、search 和 indexOf,但一切都给我同样的错误,我做错了什么?
我知道我得到了所有的 a 标签,第一个警报返回它们的总数。 这是我所拥有的:
// get all the link tags from the page
var a = document.getElementsByTagName('a');
//alert(a.length)
for (var i = 0; i < a.length; i++)
{
// check which links have an anchor within them
if(a[i].search("#") > 1)
{
alert("yes");
}
else
{
alert("no");
}
}
【问题讨论】:
-
a[i]是一个 DOM 元素(如错误所示)。如果您想访问该元素的href值,请执行a[i].href或a[i].getAttribute('href')。 -
我会选择 a[i].getAttribute('href');
标签: javascript dom search