Reputation: 18908
I'm trying to get an array of elements that have attribute names that start with "temp" (not the attribute value, or I'd use querySelectorAll
).
However, it seems that I can't quite get the xpath expression correct. Here is what seems to be the closest I've come up with:
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>
I would assume that would give me the 3 divs that contains at least 1 attribute with "temp."
What am I missing?
Upvotes: 3
Views: 77
Reputation: 474191
I think you are looking for matching the elements with your XPath while applying the attribute name check as a filtering condition:
//*[@*[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>
Upvotes: 3