简体   繁体   中英

Check if element exists in a jQuery collection

Lets say I have this html:

<div class="test"></div>
<div class="test"></div>
<div class="test" id="target"></div>

Somewhere in my code I call:

var $divs = $('.test');

Later, I call:

var $target =$('#target');

Now, I'd like to check if $target is in $divs

I expected the below to log true on the the 3rd iteration but I get false 3 times:

var $divs = $('.test');
var $target =$('#target');
console.log($target);
$divs.each(function(){
      console.log($(this));
      console.log($(this) == $target);  // expected true on 3rd iteration
});

Looking at the console. it's obvious why this returns false.

What would be the correct way to check if $divs contains $target ?

Here is a jsFiddle

Your condition returns false as an object is not equal to another object in JavaScript. As an example:

$(window) !== $(window) 

This is because each time the jQuery constructor is called a new object is created.

In your case if you get the wrapped object from the collection your condition will return true for the target element:

$target.get(0) === this;

try to check by id,

$divs.each(function(){
      console.log($(this));
      console.log($(this).attr("id") == $target.attr("id"));  
});

Change console.log($(this) == $target) into this console.log($(this).is($target)) .

For comapring two objects in jquery, use (a.is(b)) ie .is() function

 var $divs = $('.test');
    var $target =$('#target');
    console.log($target);
    $divs.each(function(){
          console.log($(this));
          console.log($(this).is($target)); 
    });

jsfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM