queryselector获取元素,其中属性以"xxx"开头 [英] queryselector get elements where attribute starts with 'xxx'
问题描述
我正在尝试获取属性以 comp-
开头的所有项目.因此,请将该HTML用作参考:
I am trying to get all items where the attribute starts with comp-
. So, take this html for reference:
<h1 comp-Color="red">Hello, world!</h1>
<h1 comp-Background="black">Hello, world!</h1>
<h1 comp-Age="123">Hello, world!</h1>
我已经尝试过这样做,但是似乎不起作用:
I have tried doing this, but it doesn't seem to work:
let e = document.querySelectorAll('[^comp-]');
这样做会给我以下错误:
Doing so gives me the following error:
未捕获的DOMException:无法对'Document'执行'querySelectorAll':'[^ comp-]'不是有效的选择器.
Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': '[^comp-]' is not a valid selector.
推荐答案
您可以将xpath用于此类任务
You can use xpath for such a task
例如要获取以 xxx-
开头的所有属性,请使用xpath字符串
e.g. to get all attributes that start with xxx-
you use the xpath string
'//*/attribute::*[starts-with(name(), "xxx-")]'
或者 attribute ::
的简写是 @
-使得上面的内容
or, shorthand for attribute::
is @
- which makes the above
'//*/@*[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)
});
进一步阅读: MDN上的XPATH
我还没有找到更多详细文档的可靠来源. document.evaluate
在除IE之外的所有浏览器中都可用,但是,我确实记得有一个IE的xpath库-不确定它的完整性如何
I haven't found a reliable source for more detailed documentation. document.evaluate
is available in all browsers except IE, however, I do recall there is a library for xpath for IE - not sure how complete it is
基于
这篇关于queryselector获取元素,其中属性以"xxx"开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!