I am working a lot with nodes before they are attached to the main page’s DOM; and I need to perform some work depending on whether or not a given node is contained within the main document or not.
My current method is to walk up the parents, via:
if this.el$.closest("body").length > 0
Is there a more appropriate way to do this? (Preferrably one that doesn’t have to walk all of the node’s ancestors?)
You have several options which execute at several different speeds.
See Performance Test
For this test I copied a huge amount of html to traverse over, I copied the source of one of the jQuery pages into a fiddle, stripping out all the script tags leaving only the body and the html in between.
Feel free you use document instead of “body” and vice-versa or add more tests but it should give you the general idea.
Edit
I updated the performance test to use the correct syntax for contains as the previous one was incorrect and always returned true even if the element did not exist. the blow now returns true if the element exists but if you specify a selector which doesn’t exist it will return false.
I also added the suggested alternative mentioned by MrOBrian in the comments of the question which is again slightly faster than contains.
Nice one MrOBrian.
Edit
Here is the jsPerf performance test with all the nice charts.
Thanks Felix Kling for spotting the issue and helping me fix the jsPerf tests.
Added more test results from the comments, this one is really good:
jsPerf performance test: dom-tree-test-exists