user3421410 user3421410 - 1 year ago 85
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


(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


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 Source

In all modern browsers:

document.querySelectorAll('div > * > * > a');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download