pretty simple question here: is there a better way to write this code?
$('.icMenu span.menu').each(function() {
// do something
});
$('.icMenu span.menu').click(function() {
// do something else
});
I'm using the same selector twice, is there a better way I should be writing this?
Use chaining as already suggested
$('.icMenu span.menu').each(function() {
// do something
}).click(function() {
// do something else
});
Or simply use a local variable to avoid running the jQuery selector twice:
var $menus = $('.icMenu span.menu');
$menus.each(function() {
// do something
});
$menus.click(function() {
// do something else
});
The key is to always avoid running the selector more than once as that has a large overhead.
If your elements are ever dynamically created, you would move the click to a delegated on event handler anyway, so your question would become a non-issue (they would be the same selector, but separated in time):
$(document).on('click', '.icMenu span.menu', function(){
// Do something on dynamically created elements
});
In a delegated event handler, the selector is only run after the event is caught on an ancestor (in this case document). The function is then applied to any matching elements that caused the event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With