Specify multiple selectors with jQuery

Posted in Javascript -

Today's jQuery post is a quick tip for writing more concise code, which is to specify multiple selectors using commas if the same function should be applied to multiple elements.

Bad Example

For example, to assign the same click handler to the elements #foo, #bar and #baz you could do this:

$('#foo').click(function() {
    common_function();
});
$('#bar').click(function() {
    common_function();
});
$('#baz').click(function() {
    common_function();
});
function common_function() {
    // do something here
}

This is far from ideal because it is rather verbose, but at least the common stuff that's done is done in a common function so if it needs to be changed it can be changed in one place.

Good Example

A far better way to do it is like this, where each selected element is separated by a comma:

$('#foo, #bar, #baz').click(function() {
    // do something here
});

This is much more concise and compact way of achieving the same thing and means a separate common function does not need to be called.

Further Reading

Read the Selectors/multiple page of the jQuery online documentation for details and examples.



Related posts:


Comments