Check if element contains another one in jQuery

Just use .find() and check if returns an element, like this:

$(".bt_repondre").click(function(){
    comment = $(this).parent().parent().parent();
    if (! comment.find('.comment_full').length) {
       comment.append('add');
    }
});

You can use .has and .length:

if (comment.has('.comment_full').length) {
    // It has that element
}
  • .find will iterate over all of the descendants, but .has will stop once a descendant that matches the selector has been found. It might run faster.

  • .length just checks to see if the length of the resulting set of elements is non-zero.


Most of these answers are incorrect. You must pass a DOM node not a jQuery element for $.contains to work properly per https://api.jquery.com/jQuery.contains/.

For example, this is how you would determine if $('#a') contains $('#b).

HTML:

<div id="a">
  <div id="b"></div>
</div>

JavaScript:

var $a = $('#a');
var $b = $('#b');
var contains = $.contains($a.get(0), $b.get(0));
console.log('contains', contains);
// outputs `true`