user3421410 user3421410 - 3 months ago 14
HTML Question

JavaScript Query to get children similar to an XPath search

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.

Answer

In all modern browsers:

document.querySelectorAll('div > * > * > a');
Comments