Get a list of elements with attribute names that start on a specific string using XPath

I'm trying to get an array of elements that have attribute names starting with "temp" (not an attribute value, or I would use querySelectorAll

).

However, I can't seem to get the correct xpath expression. Here's what seems to be the closest I've encountered:

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>
      

Run codeHide result


I would guess I would give me 3 divs that contain at least 1 attribute with "temp."

What am I missing?

+3


source to share


1 answer


I think you are looking to match the elements with your XPath by applying the attribute name validation as a filter 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>
      

Run codeHide result


+3


source







All Articles