【问题标题】:Finding a DOM element by attribute name and value using regex使用正则表达式按属性名称和值查找 DOM 元素
【发布时间】:2019-05-29 15:12:44
【问题描述】:

我正在尝试使用 document.querySelector 和正则表达式查找具有属性的锚点 dom 元素,例如 href='/post/3534'。

比如,

document.querySelector("a[href='/post/(/[0-9]+/g)']")

但它显然不起作用。

什么是我的目的的正确语法? 非常感谢您的帮助。

【问题讨论】:

    标签: javascript regex css-selectors


    【解决方案1】:

    选择器不接受正则表达式——你能做的最好的就是querySelectorAll<a>s,然后是.findhref与你的条件匹配的那个:

    const foundA = Array.prototype.find.call(
      document.querySelectorAll('a[href^="/post/"]'),
      a => /^\/post\/[0-9]+/.test(a.getAttribute('href'))
    );
    if (foundA) {
      console.log(foundA.getAttribute('href'));
    }
    <a href="foobar">foobar</a>
    <a href="/post/words">words</a>
    <a href="/post/1234">numbers</a>

    【讨论】:

      猜你喜欢
      • 2012-10-28
      • 1970-01-01
      • 2013-04-29
      • 1970-01-01
      • 1970-01-01
      • 2012-06-07
      • 2014-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多