beginerdeveloper
beginerdeveloper

Reputation: 845

How to compare 2 DOM elements?

I want to alert b if element is $("[id$=linkbuttonabsd]") and alert a otherwise.

JavaScript code:

$("body").find("a").click(function (e) {
    var herf = $("body").find("a");
    var link = $("[id$=linkbuttonabsd]");
    var isb = false;
    for (var i = 0; i < herf.length; i++) {
        if (herf[i] == link) {
            isb = true;
        }
    }
    if (isb) {
        alert("b");
    } else {
        alert("a");
    }
});

But I can not achieve this by herf[i] == link. How should it be done?

Upvotes: 0

Views: 96

Answers (2)

Satpal
Satpal

Reputation: 133403

$.fn.is() can be used.

Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.

if(herf.eq(i).is(link)){
    //Condition is ture
}

Also to get the element at specified index use .eq() rather than []

You don't need to loop through the objects. Code can be reduced to

$("body a").click(function(e) {
    var herf = $("body a");
    var link = $("[id$=linkbuttonabsd]");
    var isb = herf.is(link);

    if (isb) {
        alert("b");
    } else {
        alert("a");
    }    
});

Upvotes: 3

Ashish Kumar
Ashish Kumar

Reputation: 3039

Try using $.is to match an element. Here is the example:

if ($(herf[i]).is("#linkbuttonabsd")) {
    isb = true;
}

Upvotes: 0

Related Questions