For example, if I have a snippet of a document:
<div> <!-- I have a reference to this: "outerDiv". -->
<p> <!-- This is the <p> I want to select. -->
<div>
<p> <!-- I don't want to select this <p>. --> </p>
</div>
</p>
</div>
(This is a hypothetical document. HTML parsers would not actually construct a DOM that looks like this.)
and a reference to the outermost <div>
element, I'd like to somehow use outerDiv.querySelectorAll('p')
to select only the <p>
elements that are direct children of the outer <div>
.
I can't use outerDiv.childNodes
and search for the <p>
elements because I actually have a selector that is much longer than "p"
(e.g., it might look like "p > a > b"
). I also don't have control over the HTML and can't use jQuery or other JavaScript libraries.
It's also not sufficient to prepend "div > "
to the selector and apply it from outerDiv.parentNode
since the inner <p>
also matches "div > p"
.
Is there a clean way to do this without having to parse the CSS selector myself, too much?
Can you use body > div > p
or whatever lies outside of the outermost div?