1

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

Wesley Smith
  • 19,401
  • 22
  • 85
  • 133
  • 2
    use `$(this).is($target)` – Pranav C Balan Dec 05 '15 at 05:47
  • @PranavCBalan Thank you! I knew I had done this before but could not remember for the life of me how – Wesley Smith Dec 05 '15 at 05:49
  • @Vohuman As I understand it, because `[div#target.test, context: document, selector: "#target"]` != `[div#target.test, context: div#target.test]`. Even though they refer to the same dom element, the objects themselves are different. but Im all for learning a more specific reason if you have time – Wesley Smith Dec 05 '15 at 05:54

3 Answers3

1

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;
Ram
  • 143,282
  • 16
  • 168
  • 197
  • Thank you for taking the time to explain that. I did not realize that was the case but it totally makes since now that you point it out. I didn't even consider drilling down to the DOM element like that but that also makes perfect sense now. – Wesley Smith Dec 05 '15 at 06:06
0

try to check by id,

$divs.each(function(){
      console.log($(this));
      console.log($(this).attr("id") == $target.attr("id"));  
});
Azad
  • 5,144
  • 4
  • 28
  • 56
0

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

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

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

jsfiddle

Har devgun
  • 533
  • 6
  • 25