Best way to find out if element is a descendant of another

Viewed 42785

I am in the process of implementing jQuery, and taking out Prototype libraries in my codebase, and I am wondering if you could give me the best way to implement this functionality in jQuery. I am familiar with the jQuery ancestor>descendant syntax, but just want to check if an element is a descendant by true of false, like the code below: can someone give me the most efficient jQuery solution for this ?

<div id="australopithecus">
  <div id="homo-herectus">
    <div id="homo-sapiens"></div>
  </div>
</div>

$('homo-sapiens').descendantOf('australopithecus');
// -> true

$('homo-herectus').descendantOf('homo-sapiens');
// -> false
11 Answers

I would think you could take advantage of CSS style selection here, with returned length..

$('#australopithecus #homo-sapiens').length // Should be 1
$('#homo-sapiens #homo-herectus').length // Should be 0

Not exactly true/false, but checking 0/1 as a boolean should work. :)

Alternately, you could do something like $('#parent').find('#child') and check the length there.

How about


$("#homo-herectus").parents().is("#australopithecus");

You can use the is() function like so:

alert($('#homo-sapiens').is('#australopithecus *'));
// -> true

alert($('#homo-herectus').is('#homo-sapiens *'));
// -> false

You could attempt to .find() it in the Elements .children()

$("#lucy").find("#homo-erectus").length;

Or the opposite direction:

$("#homo-erectus").parents().find("#lucy").length;
function descendantOf(parentId, childId) {
   return ( $('#'+parentId+' > #'+childId).length === 1 );
}

That should work.

As was pointed out in the comment below, if you don't want it to be just direct descendants:

function descendantOf(parentId, childId) {
   return ( $('#'+childId, $('#'+parentId)).length === 1 );
}

Supposing to rewrite your initial statement in:

$('#homo-sapiens').descendantOf('#australopithecus');

try to plugin:

(function($) {
    $.fn.descendantOf = function(parentId) {
        return this.closest(parentId).length != 0;
    }
})(jQuery)
Related