javascript - queryselector 获取属性以 'xxx' 开头的元素

标签 javascript

我正在尝试获取属性以 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 库 - 不确定它有多完整

google wicked good xpath

这是基于

javascript-xpath

关于javascript - queryselector 获取属性以 'xxx' 开头的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41623353/

相关文章:

javascript - 为 D3 可视化创建平均 Y 线?

javascript - Google 脚本 - Google 表格 - 需要修改脚本以跳过任何具有匹配变量的文本行

javascript - 将学生添加到虚拟教室

javascript - 获取单击上下文菜单项的 Extjs 网格

javascript - 更新 Controller 变量并在指令 View 中使用它( Angular 1.5)

javascript - 在 JavaScript 中,什么是 event.isTrigger?

javascript - PhoneGap/Cordova for android 文件插件错误代码 1

javascript - 谷歌地图 API : Geocoder: unknown property function:

javascript - 变量不修改 divCount

javascript - HTML 页面部分的小 map 在视口(viewport)中显示为固定 anchor