Specify multiple selectors with jQuery
Posted December 26th, 2009 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:
- Set multiple attributes at once with jQuery (Tuesday, December 15th 2009)
- Assign and remove a click handler from an element with jQuery (Tuesday, December 1st 2009)
- Loop through selected elements with jQuery (Revised) (Tuesday, April 14th 2009)
- Get the total number of matched elements with jQuery (Tuesday, March 31st 2009)
- Attaching an event to an element with jQuery (Tuesday, February 24th 2009)
- How to get and set form element values with jQuery (Thursday, November 13th 2008)

Comments
blog comments powered by Disqus