【问题标题】:How can I find all <a> tags that match a certain pattern? [duplicate]如何找到与特定模式匹配的所有 <a> 标记? [复制]
【发布时间】:2020-12-04 16:39:37
【问题描述】:

我想匹配href 中所有具有example.com/appa 标签。如何使用 JavaScript 做到这一点?

【问题讨论】:

标签: javascript dom queryselector


【解决方案1】:

您可以将querySelectorAllcss attribute selector 一起使用:

document.querySelectorAll('a[href="www.example.com"]')

【讨论】:

  • 这是最高效的方式吗?
  • @Shamoon 我想这不仅仅是一种“原生”方式,但我没有针对其他“算法”方式对其进行测试,但肯定是更清洁和可维护
【解决方案2】:

您可以选择所有a 元素,然后检查它们是否具有值为example.com/apphref

const a = document.getElementsByTagName("a");
let els = [];

for (let i = 0; i < a.length; i++) {
  if ((a[i].getAttribute("href") == "example.com/app") || (a[i].getAttribute("href") == "https://example.com/app")) {
    els.push(a[i]);
  }
}

console.log(els);
<a href="example.com/app" id="1">1</a>
<a href="https://example.com/app" id="2">2</a>
<a href="example.com/app" id="3">3</a>
<a href="" id="4">4</a>
<a id="5">5</a>
<a href="https://example.com/app" class="6">6</a>
<a href="https://example.com/app">7</a>

【讨论】:

    猜你喜欢
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    • 2022-10-02
    • 2013-06-16
    • 1970-01-01
    • 1970-01-01
    • 2015-12-03
    • 2012-02-29
    相关资源
    最近更新 更多