I have a function that I want to return true or false.
Inside the function I iterate through some elements on the page and check their values.
But if I put a return statement inside the iterator, it will return from the anonymous function right? (and not the outer function).
function someElementHasZeroValue() {
$('.some-class').each(function(){
if($(this).html() == '0'){
return true;
}
});
return false;
}
So this function always returns false no matter what.
What is the best way to do this? The solution below seems to work but it doesn’t seem very elegant.
function someElementHasZeroValue() {
elements_found_with_zero_value = 0;
$('.some-class').each(function(){
if($(this).html() == '0'){
elements_found_with_zero_value += 1;
}
});
if(elements_found_with_zero_value > 0){
return true;
}else {
return false;
}
}
More generally, does anyone know why Javascript requires you to iterate through elements with an anonymous function as opposed to a normal iterator like most languages, or is there some way to do it I’m not aware of?
You are using jQuery, not pure Javascript. You could do a normal loop:
Alternatively, you could do this in a more jQuery-like way: