Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - how to check if two elements are the same?

I need to pass an element to a function and then match that specific element while traversing parent. The catch (for someone clueless like me) is that this element doesn't have an id. In the following example, I want every element to turn pink except the one clicked on that should turn yellow

function colorize(element) {     element.parent().find('span').each(function() {         if ($(this)===element) { // the problem is this is always false             $(this).css('background','yellow');         } else {             $(this).css('background','pink');         }     }); } $('span').click(function() {     colorize($(this)); }); 
like image 843
A-OK Avatar asked Oct 09 '11 11:10

A-OK


People also ask

How can I check if two values are equal in jQuery?

Approach 1: Use is() method to check both selected elements are same or not. It takes an element as argument and check if it is equal to the other element.

How to check two strings are equal in jQuery?

e.g 0 == "" is true but "" == '0' is false and many more. Similarly, you may use !== instead of != for checking opposite conditions.

How do you check if two values are the same in HTML?

To check if a variable is equal to all of multiple values, use the logical AND (&&) operator to chain multiple equality comparisons.


2 Answers

Comparing JQuery objects will never return true, because each JQuery object is a a new object, even if their selectors are equal.

To compare elements, you have to check whether the DOM elements are equal:

this === element.get(0); 
like image 173
Rob W Avatar answered Sep 22 '22 07:09

Rob W


You can use the jQuery is() function. The original answer can be found here.

function colorize(element) {     element.parent().find('span').each(function() {         if ( $(this).is(element) ) {             $(this).css('background','yellow');         } else {             $(this).css('background','pink');         }     }); } 
like image 42
Nikola Obreshkov Avatar answered Sep 22 '22 07:09

Nikola Obreshkov