Element Has Parent

Benchmark created by Fardin on


Description

Addressing the issue provided in the following Stackoverflow question: Check if class exists somewhere in parent - vanilla JS http://stackoverflow.com/q/16863917/717221

Gist: https://gist.github.com/Fardinak/057f74cc22b15db35044

Preparation HTML

<div id="the-parent" class="also has class">
  <div>
    <div class="im-yo-dad">
      <div id="missing-child"></div>
    </div>
  </div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Setup

function hasParent(element, parentSelector) {
      var potentialParents = document.querySelectorAll(parentSelector);
      for(i in potentialParents) if(potentialParents[i].contains(element))
        return potentialParents[i];
      return false;
    }
    
    function hasSomeParentTheClass(element, classname) {
      if (element.className.split(' ').indexOf(classname)>=0) return true;
      return element.parentNode && hasSomeParentTheClass(element.parentNode, classname);
    }
    
    
    var child = document.getElementById('missing-child');

Test runner

Ready to run.

Testing in
TestOps/sec
Query Selector - ID
hasParent(child, '#the-parent')
ready
Query Selector - Class
hasParent(child, '.also')
ready
Query Selector - Mix
hasParent(child, '#the-parent.also.has.class')
ready
Recursive
hasSomeParentTheClass(child, 'also')
ready
For the curious mind
hasParent(child, '#the-parent > div .im-yo-dad')
ready
jQuery - ID
jQuery(child).parents('#the-parent')
ready
jQuery - Class
jQuery(child).parents('.also')
ready
jQuery - Mix
jQuery(child).parents('#the-parent.also.has.class')
ready
jQuery - Complex
jQuery(child).parents('#the-parent > div .im-yo-dad')
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Fardin on