JQuery: select by class after changing the class to .addClass () or .attr ()

I have 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 with the class name defined in the source HTML document, however, after manipulating the class name with jQuery, the img element will not respond to selectors using its new class.

In other words, when you run the above code, if you press " off " img, it will call the first function and change the class to " on ". However, when you click this image again, the second function does not start (as I expected), but rather starts the first time. It is as if the selector is reading the old DOM, not the updated version. What am I doing wrong here?

Firefox 3.6.3 - jQuery 1.4.2

+6
jquery
source share
3 answers

You can use .live() to do what you want, for example:

 $(function() { $("img.off").live('click', function() { alert('on'); $(this).attr('class', 'on'); }); $("img.on").live('click', function() { alert('off'); $(this).attr('class', 'off'); }); }); 

When you execute $(selector).click() , you find the elements that match at that time and attach the handler to the click event ... when their class changes later, it does not matter for this, the handler is attached. .live() works differently, actually taking care of choosing a selector when an event occurs .

Also, depending on your example / what you end up with after this, something like .toggleClass() might simplify it for you, for example:

 $(function() { $("img.off, img.on").live('click', function() { $(this).toggleClass('on off'); alert($(this).attr('class')); }); }); 
+11
source share

Try with live() :

 $(document).ready(function() { $("img.off").live('click', function() { alert('on'); $(this).attr('class', 'on'); }); $("img.on").live('click', function() { alert('off'); $(this).attr('class', 'off'); }); }); 
+3
source share

You need to either cancel the click callback after changing the class, or use it . live ()

+2
source share

All Articles