Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if element contains another one in jQuery

I found many related things on Stack Overflow but not applicable for my case.

It's all in this exemple, I need to check if an element contains another one, and if yes, append something.

$(".bt_repondre").click(function(){
    comment = $(this).parent().parent().parent();
    //I want to check if comment contains a .comment_full element, if no, append.
    comment.append('add');
});

Hope you can help me, I tried so many things...

like image 749
Jeff B. Avatar asked Nov 01 '12 17:11

Jeff B.


1 Answers

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.

like image 57
Blender Avatar answered Oct 28 '22 02:10

Blender