Ben Nadel looks at the Node.contains() method, which determines if one node is contained within, or is equal to, another node. This is being documented in an attempt to drive it into Ben’s thick skull.
This post is primarily a “Note to Self”; but, the other day, I was reading through the Mozilla Developer Network (MDN) site – as you do – and I noticed that the Node interface in the Document Object Model (DOM) API has a .contains() method. This method checks to see if one node is contained within, or is equal to, another node. In jQuery, I used to use the .contains() method all the time for this type of investigation. However, when it came to the native DOM, I’ve historically walked up the tree comparing object references. I’m shocked that I didn’t know that the native DOM API contained a similar helper. As such, I’m documenting it here in an effort to drive this information into my head.
As you can see from earlier posts, like “Tracking Click Events Outside The Current Component In Angular 2 Beta 1”, if I wanted to compare the relative relationship of two nodes in the DOM, I would start at one node and continue walking up the parentNode chain until the two references were the same; or, until I ran out of parentNode references to inspect. Such an approach looked something like this:
This worked well. And, it wasn’t all that complicated. But, it turns out that I can completely offload this logic to the native Node.contains() method. To see this in action, I’ve created a simple demo in which you can click anywhere in the page and I’ll log to…