Reputation: 347
I'm trying to write a query in Javascript that will look for patterns in HTML such as finding "a" elements that are child elements of a div's child elements. I can do this in XPath with something like
//div/*/*/a
(Ideally, I would like to be able to return the top level divs here as well as the a elements)
I am stuck trying to do this in Javascript. Something like
document.getElementsByTagName('div')[*][*].getElementsByTagName('a');
does not work: [*] does not work (I was hoping it would search all direct children) and .getElementsByTagName('a') looks through all descendants of whichever node we are on, not just direct children. Is there a simple way of writing a JS query similar to the XPath one? Thanks.
Upvotes: 1
Views: 498
Reputation: 33658
You can evaluate XPath expressions directly using Document.evaluate
in browsers that support DOM Level 3 XPath or selectNodes
under Internet Explorer.
function evalXPath(expr) {
var items;
if (document.evaluate) {
var result = document.evaluate(expr, document, null, XPathResult.ANY_TYPE, null);
var item;
items = [];
while (item = result.iterateNext()) {
items.push(item);
}
} else if (document.selectNodes) {
items = document.selectNodes(expr);
}
return items;
}
var items = evalXPath('//div/*/*/a');
console.log('found ' + items.length + ' items');
<div>
<span>
<span>
<a href="#">one</a>
<a href="#">two</a>
</span>
</span>
</div>
<div>
<span>
<span>
<a href="#">three</a>
</span>
<span>
<a href="#">four</a>
</span>
</span>
</div>
Upvotes: 0
Reputation: 338316
In all modern browsers:
document.querySelectorAll('div > * > * > a');
Upvotes: 1