jQuery: selecting by class after class change by .addClass() or .attr()
Posted
by Sosh
on Stack Overflow
See other posts from Stack Overflow
or by Sosh
Published on 2010-05-25T12:12:53Z
Indexed on
2010/05/25
12:21 UTC
Read the original article
Hit count: 230
jQuery
I have some jQuery code something like this:
$(document).ready(function() {
$("img.off").click(function() {
alert('on');
$(this).attr('class', 'on');
});
$("img.on").click(function() {
alert('off');
$(this).attr('class', 'off');
});
});
The selector works fine for images that have the class name defined in the original HTML document, however after manipulating the class name with jQuery, the img item will not respond to selectors using it's new class.
In other words, running the above code, if you click an 'off
' img, it will trigger the first function, and change the class to 'on
'. However, clicking this image again does not trigger the second function (as I would have expected), but rather triggers the first again. It's as if the selector is reading the old DOM rather than the updated version. What am I doing wrong here?
Firefox 3.6.3 - jQuery 1.4.2
© Stack Overflow or respective owner