【发布时间】:2019-05-29 15:12:44
【问题描述】:
我正在尝试使用 document.querySelector 和正则表达式查找具有属性的锚点 dom 元素,例如 href='/post/3534'。
比如,
document.querySelector("a[href='/post/(/[0-9]+/g)']")
但它显然不起作用。
什么是我的目的的正确语法? 非常感谢您的帮助。
【问题讨论】:
标签: javascript regex css-selectors
我正在尝试使用 document.querySelector 和正则表达式查找具有属性的锚点 dom 元素,例如 href='/post/3534'。
比如,
document.querySelector("a[href='/post/(/[0-9]+/g)']")
但它显然不起作用。
什么是我的目的的正确语法? 非常感谢您的帮助。
【问题讨论】:
标签: javascript regex css-selectors
选择器不接受正则表达式——你能做的最好的就是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>
【讨论】: