Search code examples
javascriptjqueryrefactoringprototypejs

Can this snippet of Javascript be simplified more with jQuery?


I have the following snippet of Javascript, which is just attaching an onclick to a button and then updating the text of an em tag underneath it. I'm slowly trying to educate myself and work with jQuery more as I've found to like the syntax a lot more and for some tasks, it's more of a pleasure to work with.

Some of the best examples I've found have come from Stackoverflow, so I come once again, to see how this could refactored and improved with jQuery; any thoughts?

$$('em.green').each(function(em) { 
  em.up('button').onclick = function() { 
    em.update('Saving...') 
  }; 
});

Thanks!


Solution

  • Here is a line by line translation from your prototype code. Not a lot different:

    $('em.green').each(function(i, em) {
        $(em).closest('button').click(function() { 
            $(em).html('Saving...') 
        })
    });
    

    IMO the prototype version looks just as nice if not nicer (without $ sprinkled everywhere).