Oto Shavadze
Oto Shavadze

Reputation: 42863

Check existing IDs using jquery

I have several span tags and I need to check for some span tag with concrete id if these exist.

The below example return false though. What could be wrong? I have an example available at this link.

html:

<div id="recipient_list">
    <span id="r1"></span>
    <span id="r4"></span>
    <span id="r5"></span>
</div>

javascript:

function check_in_recipient_list (id) {
    $("#recipient_list > span").each( function () {
        existed_id = $(this).attr("id");

        if (existed_id === "r"+id+"") {
            return true;
        }
    });
    return false;
} 

$(document).on("dblclick", function () {
    alert( check_in_recipient_list(1) );
})

Upvotes: 0

Views: 75

Answers (3)

madmanul
madmanul

Reputation: 420

try

$("#recipient_list > span[id='"+id+"']").lenght>0

Upvotes: 0

user57508
user57508

Reputation:

Why don't you restate your function, like

function check_in_recipient_list (id) {
    return $("#recipient_list > span#r" + id).length > 0;
}

if hierarchy/dependency doesn't matter, and elements with the id #r* can only be under #recipient_list, you can also go for

function check_in_recipient_list (id) {
    return $("span#r" + id).length > 0;
}

and .. furthermore, if elements with the id #r* are only span-elements, you can also do

function check_in_recipient_list (id) {
    return $("#r" + id).length > 0;
}

Upvotes: 3

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382514

Your return is exiting from the callback you give to each, not from the check_in_recipient_list function.

Do this :

function check_in_recipient_list (id) {
    var found = false;
    $("#recipient_list > span").each( function () {
        var existed_id = this.id; // faster and simpler than using attr, and don't forget var
        if (existed_id === "r"+id+"") {
            found = true;
            return false; // this breaks the iteration
        }
    });
    return found;
} 

Note that the whole could be made simpler :

function check_in_recipient_list (id) {
    return $("#recipient_list > span#r"+id).length>0
}

Upvotes: 1

Related Questions