When targeting multiple class with JQuery, is each()
mandatory ?
With a practical example, this $('.myClass').html('Hello');
and this $('.myClass').each( function() { $(this).html('Hello'); };
have, at first glance, the same outcome. I would tend to think that using each()
to target multiple class is best practice but am I wrong?
Advertisement
Answer
With jQuery, a basic design goal was to do as much iteration implicitly as possible. So, if you want to add a class to all elements with another class,
$(".some-class").addClass("another-class");
is all you need. Internally, it effectively does .each()
for you. It’s a matter of opinion, but it would be silly to explicitly use .each()
for something like that.
In other cases, it depends on exactly what you’re doing. Clearly .each()
is called for when you have a significant or “interesting” amount of work to do for each element in a jQuery object. Some APIs allow a function to be passed and performs an implicit iteration that basically is again like .each()
; others do not, however.
So it depends on the situation. Note that another possibility is to create your own jQuery method that perform the iteration internally to your own specifications.