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

前端 未结 4 564
感情败类
感情败类 2020-12-16 09:59

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

4条回答
  •  猫巷女王i
    2020-12-16 10:24

    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.

    function colorize(element) {
        element.parent().find('span').each(function() {
            $(this).css('background','pink');
        });
    
        element.css('background','yellow');
    }
    

    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:

    var o1 = {};
    var o2 = {};
    o1 !== o2;
    

    You can work around this by removing the jQuery wrapper:

    function colorize(element) {
        var realElement = element[0];
    
        element.parent().find('span').each(function() {
            if (this === realElement) {
                $(this).css('background','yellow');
            } else {
                $(this).css('background','pink');
            }
        });
    }
    

    This way, you're comparing DOM elements to DOM elements, and not apples to oranges or objects to objects.

提交回复
热议问题