我正在尝试获取一个元素数组,这些元素的属性名称以“temp”开头(不是属性值,否则我会使用 querySelectorAll
)。
但是,我似乎不能完全正确地得到 xpath 表达式。这似乎是我想出的最接近的:
let els = Array.from(document.evaluate(
`//*/@*[starts-with(name(.), 'temp')]`,
document,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null
).singleNodeValue);
console.log(els);
<div temp-callback="1" temp-post-callback="4"></div>
<div temp-callback="2"></div>
<div></div>
<div temp-callback="8" temp-post-callback="7"></div>
我假设这会给我 3 个 div,其中至少包含 1 个带有“temp”的属性。
我错过了什么?
最佳答案
我认为您正在寻找与 XPath 匹配的元素,同时应用属性名称检查作为过滤条件:
//*[@*[starts-with(name(), 'temp')]]
var result = document.evaluate("//*[@*[starts-with(name(), 'temp')]]", document, null, XPathResult.ANY_TYPE, null);
var node = result.iterateNext();
var nodes = [];
while (node) {
nodes.push(node);
node = result.iterateNext();
}
console.log(nodes);
<div temp-callback="1" temp-post-callback="4"></div>
<div temp-callback="2"></div>
<div></div>
<div temp-callback="8" temp-post-callback="7"></div>
关于javascript - 使用 XPath 获取具有以特定字符串开头的属性名称的元素列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44962056/