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));
});
You can use the jQuery
is()
function. The original answer can be found here.Use
isEqualNode
Or use
isSameNode
(deprecated)You don't have to. You're always applying the special style to one specific element, so color them all, and then change the color of the specific element.
The problem with your comparison was that you were comparing two objects (jQuery objects). When comparing objects, unless they're pointing to the same thing, they are considered unequal:
You can work around this by removing the jQuery wrapper:
This way, you're comparing DOM elements to DOM elements, and not apples to oranges or objects to objects.
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: