Reputation: 2727
I have a list of divs that may or may not have a class "highlight" assigned to them.
<div id='1' class='box'></div>
<div id='2' class='box highlight'></div>
<div id='3' class='box'></div>
I am using Jquery each() to identify which one has the class highlight assigned to it and grabbing the id.
$('.box').each(function(){
if ($(this).hasClass('highlight')){
var id = $(this).attr('id');//get the id
console.log('It has the class = ' + id);//this shows correctly
}
});
//outside of the each()
console.log('id = ' + id);//this does not show the id "undefined"
When I try to retrieve the id outside of the each() it is undefined. Is there any way of retrieving it?
Upvotes: 0
Views: 1779
Reputation: 50215
Variable scope in javascript is by function, so when you declare that variable inside the .each(function() { var id; })
it is only accessible there. If you want it to be accessible outside of that function, you should declare it before the .each
, but you will still be able to use it within the .each
. Since it will be more global in scope, the variable name should be more specific then just id
, maybe use boxHighlightId
instead.
Upvotes: 0
Reputation: 8644
The var
keyword makes variable id
local to the function. Try just saying id = ...
Upvotes: 0
Reputation: 161012
update a variable in the appropriate scope:
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
}
});
Upvotes: 0
Reputation: 239581
The easiest way is to do it without a loop:
var id = $('.box.highlight').attr('id');
But to make it work with the loop, you need to declare the id
variable before the loop:
var id;
$('.box').each(function(){
if ($(this).hasClass('highlight')){
id = $(this).attr('id');//get the id
}
});
The issue is variable scope, which you should read about.
Upvotes: 3
Reputation: 106412
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);
Upvotes: 0