Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple selector chaining in jQuery?

Normally when I use a class as a selector I try to use an "id" selector with it so it does not search through the entire page but only an area where the class would be.

However I have a partial view with code in it. This partial view (common code) gets wrapped around a form tag.

I have:

<form id="Create"> // load common code in from partial view </form>  <form id="Edit"> // load common code in from partial view </form> 

Now in this common code I need to attach a plugin to multiple fields so I would do

$('#Create .myClass').plugin({ options here});  $('#Edit .myClass').plugin({options here}); 

So it's pretty much the same code. I am wondering if there is a way to make it look for either of the id's?

Edit

I am having problems with it when I have variables for my selectors

    my.selectors =      {         A: '#Create',         B: '#Edit',         Plugin: ' .Plugin'      };   $(selector.A+ selectors.Plugin, selector.B+ selectors.Plugin) 

Does not seem to run.

like image 772
chobo2 Avatar asked Apr 20 '11 21:04

chobo2


People also ask

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.

Can you chain jQuery selectors?

jQuery Method Chaining However, there is a technique called chaining, that allows us to run multiple jQuery commands, one after the other, on the same element(s). Tip: This way, browsers do not have to find the same element(s) more than once. To chain an action, you simply append the action to the previous action.

What is called chaining in jQuery?

jQuery | chaining() With jQuery, we can use do chaining which means to chain together multiple methods in a single statement on a single element. We have been using a single statement at once, but now using the chaining method we can bind multiple methods to make the code short.


2 Answers

You can combine multiple selectors with a comma:

$('#Create .myClass,#Edit .myClass').plugin({options here}); 

Or if you're going to have a bunch of them, you could add a class to all your form elements and then search within that class. This doesn't get you the supposed speed savings of restricting the search, but I honestly wouldn't worry too much about that if I were you. Browsers do a lot of fancy things to optimize common operations behind your back -- the simple class selector might be faster.

like image 158
Leopd Avatar answered Sep 21 '22 02:09

Leopd


$("#Create").find(".myClass").add("#Edit .myClass").plugin({});

Use $.fn.add to concatenate two sets.

like image 21
Raynos Avatar answered Sep 22 '22 02:09

Raynos