Remember that the click
event you assigned does not run until you actually click an <img>
, so trying to get an image with the class .bob
before any click events have occurred on the <img>
elements will result in 0 elements matched (unless you have .bob
assigned to one of the <img>
elements before the page loads.
You need to retrieve the 'id' inside the button's click handler.
Also, you can make your code a little more efficient by caching the <img>
elements found (as long as you're not adding additional ones dynamically after the page loads).
var $img = $('img').click(function() {
$img.not(this).removeClass('bob');
$(this).addClass('bob');
});
$('div.button').click(function() {
var test = $img.filter('.bob').attr('id');
alert(test);
});
If you are going to be adding images dynamically, then you don't need to cache them.
$('img').click(function() {
$('img').not(this).removeClass('bob');
$(this).addClass('bob');
});
$('div.button').click(function() {
var test = $('img.bob').attr('id');
alert(test);
});