retrieving variables from a jquery each()-Collection of common programming errors

You could instead do $('.box.highlight').attr('id');

If you really want to access that variable OUTSIDE of the inner function used for .each() you need to define the variable outside of that function. Note that this won’t work quite the same way for asynchronous calls, but should with .each()

var id;
$('.box').each(function(){
    if ($(this).hasClass('highlight')){
        id = $(this).attr('id');//get the id    
        console.log('It has the class = ' + id);//this shows correctly 
    }                       
});
console.log('id', id);

Originally posted 2013-11-09 18:44:15.