Reputation: 42863
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
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
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