Node.contains: Check if a Node is a Child of Another Node

By  on  

There are loads of basic, native JavaScript methods that many developers don't know about.  Many people don't know about the Element.classList API, for example, so className management becomes another case for needing a JavaScript toolkit for even the most basic tasks.  Another case is checking for node parenting -- developers believe it requires a toolkit or a loop checking parentNode up the chain;  no so!  Nodes provide a contains method to check if one node if a parent of another:

function(parentNode, childNode) {
	if('contains' in parentNode) {
		return parentNode.contains(childNode);
	}
	else {
		return parentNode.compareDocumentPosition(childNode) % 16;
	}
}

You'll note we check for the contains method before using it, as you would probably expect, and use the rarely-known compareDocumentPosition in the case that contains isn't supported (Firefox < 9).  This method would be helpful when creating a drag & drop widget and determining moves between lists.  Anyways, before you jump to the conclusion that you need a toolkit for something that seems basic, do some quick research and hopefully you find an easier way!

Recent Features

  • By
    Create a CSS Flipping Animation

    CSS animations are a lot of fun; the beauty of them is that through many simple properties, you can create anything from an elegant fade in to a WTF-Pixar-would-be-proud effect. One CSS effect somewhere in between is the CSS flip effect, whereby there's...

  • By
    CSS Gradients

    With CSS border-radius, I showed you how CSS can bridge the gap between design and development by adding rounded corners to elements.  CSS gradients are another step in that direction.  Now that CSS gradients are supported in Internet Explorer 8+, Firefox, Safari, and Chrome...

Incredible Demos

  • By
    Chris Coyier’s Favorite CodePen Demos IV

    Did you know you can triple-heart things on CodePen? We’ve had that little not-so-hidden feature forever. You can click that little heart button on any Pen (or Project, Collection, or Post) on CodePen to show the creator a little love, but you can click it again...

  • By
    WordPress-Style Comment Controls Using MooTools or jQuery

    WordPress has a nice little effect on the Admin Dashboard where it shows and hides the comment control links when you mouseover and mouseout of the record's container. Here's how to achieve that effect using MooTools or jQuery. The XHTML Notice that we place the links into...

Discussion

  1. MaxArt

    I’m not sure this works. Shouldn’t the function always return a boolean?

    If I compare an element with one of its children, with compareDocumentPosition I get 4. If I compare an element with its parent, I get 2.

    That’s how I used to polyfill the function:

    // 16 === Node.DOCUMENT_POSITION_CONTAINED_BY
    Node.prototype.contains = function(node) {
        return (this.compareDocumentPosition(node) & 16) !== 0 || this === node;
    }
    
    • Nick Williams

      You’re right, compareDocumentPosition returns a bitmask, so it can represent multiple values at once. e.g.

      var parent = document.createElement("div");
      var child = document.createElement("div");
      parent.appendChild(child);
      
      // as the article has it
      parent.compareDocumentPosition(child) % 8; // 4, truthy
      child.compareDocumentPosition(parent) % 8; // 2, truthy
      
      // how it should be
      parent.compareDocumentPosition(child) & 16; // 16, truthy
      child.compareDocumentPosition(parent) & 16; // 0, falsy
      

      John Resig’s article covers this in detail: http://ejohn.org/blog/comparing-document-position/

    • Updated, thank you!

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!