4 ms·
I use XPath on DOM when I want to find the n-th parent from a particular node. This is very easily done with XPath vs. selectors.
by ok123456 3y ago
I use XPath on DOM when I want to find the n-th parent from a particular node. This is very easily done with XPath vs. selectors.
- deleted 3y ago[deleted]
- 411111111111111 3y agolets say you have <body> <div><!-- you want this one --> ok <div id="the-child"></div> </div> <div><!-- you dont want this one --> nok <div id="the-wrong-child"></div> </div> </body> css: div:has( > #the-child) xpath: //div[@id="the-child"]/.. isnt that kinda the same? I think I'd even consider the css version to be easier to understand at a glance. If you've got full control over the Dom it'd be much better to just set an id attribute on the element in question though, as getElementById is still the best performing option
- ok123456 3y agoNow do that when you want the 8-th parent in a complex document.
- 411111111111111 3y agoI only did depth=1 because the syntax doesnt change, i still don't see a difference to speak of css: div:has( > \* > \* > \* > \* > \* > \* > \* > #the-child) (backslashes added by hn because of formatting conflict) xpath: //div[@id="the-child"]/../../../../../../../..