Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two selectors with one jQuery object

I have two divs with id's: #addNew_tab and #sendCom_tab.
I'd like clicking on either of these to trigger the same jQuery click() function.

I was thinking something like:

$("#addNew_tab", "#sendCom_tab").click(function(){
      //do stuff
});

but that doesn't work.

like image 949
Jiminy Cricket Avatar asked May 09 '12 12:05

Jiminy Cricket


People also ask

How do we combine two selectors?

The descendant combinator — typically represented by a single space (" ") character — combines two selectors such that elements matched by the second selector are selected if they have an ancestor (parent, parent's parent, parent's parent's parent, etc.) element matching the first selector.

Can we use multiple selectors in jQuery?

You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.

How many jQuery selectors are there?

So far we have covered only three standard jQuery Selectors. For a complete detail of all these jQuery selectors, you can go to through jQuery Selectors Reference.

How jQuery selectors are executed?

jQuery selector: jQuery selectors are used to selecting the HTML element(s) and allow you to manipulate the HTML element(s) in a way we want. It selects the HTML elements on a variable parameter such as their name, classes, id, types, attributes, attribute values, etc.


1 Answers

$("#addNew_tab, #sendCom_tab").click(function(){
      //do stuff
});

Changed from:

$("#addNew_tab", "#sendCom_tab")

To:

$("#addNew_tab, #sendCom_tab")

comma inside the selector("a, b") means the first plus the second; Just like with CSS selectors
(Well, it's a CSS selector...)

jQuery(selector)

Description: Accepts a string containing a CSS selector which is then used to match a set of elements.

It's equal to:

$("#addNew_tab").add("#sendCom_tab")...
like image 141
gdoron is supporting Monica Avatar answered Nov 08 '22 13:11

gdoron is supporting Monica