我正在尝试获取属性以 comp-
开头的所有项目。因此,请引用以下 html:
<h1 comp-Color="red">Hello, world!</h1>
<h1 comp-Background="black">Hello, world!</h1>
<h1 comp-Age="123">Hello, world!</h1>
我尝试过这样做,但似乎不起作用:
let e = document.querySelectorAll('[^comp-]');
这样做会出现以下错误:
Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': '[^comp-]' is not a valid selector.
最佳答案
您可以使用 xpath 来完成此类任务
例如要获取以 xxx-
开头的所有属性,您可以使用 xpath 字符串
'//*/attribute::*[starts-with(name(), "xxx-")]'
或者,attribute::
的简写是 @
- 这使得上面的内容
'//*/@*[starts-with(name(), "xxx-")]'
快速示例代码
var nodesSnapshot = document.evaluate('//*/attribute::*[starts-with(name(), "xxx-")]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var attr;
for (var i=0; i < nodesSnapshot.snapshotLength; i++ ) {
attr = nodesSnapshot.snapshotItem(i);
console.log(attr, attr.ownerElement)
};
进一步阅读:XPATH on MDN
我还没有找到更详细文档的可靠来源。 document.evaluate
可在除 IE 之外的所有浏览器中使用,但是,我记得有一个用于 IE 的 xpath 库 - 不确定它有多完整
这是基于
关于javascript - queryselector 获取属性以 'xxx' 开头的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41623353/