gospodinove gospodinove - 2 months ago 8
jQuery Question

access variables from outside .each() jquery

I am trying to access a variable set outside of an each() function and but I do not know why it does not work

Here is my code:

$(document).ready(function(){
var color = "blue";
$('.list-item').each(function(){
if($(this).hasClass('list-'+color)){
console.log('found');
}
});
});

Answer

Firstly your jQuery object is missing a $ so you're getting a syntax error which is why your code doesn't work.

That being said you can improve the logic here as the each() loop is redundant; you can select the element directly and check the length property of the resulting jQuery object. Try this:

var color = "blue";
if ($('.list-item.list-' + color).length) {
    console.log('found');
}