【问题标题】:How to search within an array?如何在数组中搜索?
【发布时间】: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].hrefa[i].getAttribute('href')
  • 我会选择 a[i].getAttribute('href');

标签: javascript dom search


【解决方案1】:

Anchor 元素有一个href 可以使用的属性:

if (a[i].href.search("#") != -1)

【讨论】:

    【解决方案2】:

    你需要检查 href 属性,像这样:

    if(a[i].href.search("#") > -1)
    

    注意索引从 0 开始,因此您需要检查 search() 的结果是否大于 -1

    【讨论】:

      【解决方案3】:

      您也可以不使用选择器进行循环。

      var aWithAnchors = document.querySelectorAll('a[href*="#"]');
      

      然后就可以获取所有的链接了:

      console.log([].map.call(aWithAnchors, function (link) {
          return link.href;
      }));
      

      【讨论】: