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)); });
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.
e.g 0 == "" is true but "" == '0' is false and many more. Similarly, you may use !== instead of != for checking opposite conditions.
To check if a variable is equal to all of multiple values, use the logical AND (&&) operator to chain multiple equality comparisons.
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);
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'); } }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With