Sharing Top Content from the Angular-sphere.

Using Node.contains() To Determine If One DOM Node Is Inside Another

  • 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…
  • 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 the console whether or not the target node is local to a known container: – – As you can see, I’m using event-delegation to handle the click…
  • Then, taking the target of the click event, I’m using the Node.contains() method to see if the click target is contained within (or is equal to) the given container.
  • And, in IE, the Node.contains() method only works for Element nodes.
  • That said, if we run this code in the browser and click outside and then inside the red box, we get the following output: – – As you can see, we were able to use the Node.contains() method to check if the click target Element was contained within (or was…

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…

Using Node.contains() To Determine If One DOM Node Is Inside Another