Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery multiple selector with $(this)

is there any way to make this work:

$(this, '#foo')

with that I want to select "this" element and #bar as well. For selecting let's say two IDs, it is just as easy as '#foo, #bar', but when I want one of those two to be "this" I cannot get it to work.

like image 271
Lukáš Řádek Avatar asked Jul 06 '13 19:07

Lukáš Řádek


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.

How do you select multiple selectors?

To select multiple elements of an html page using multiple elements selector, we pass the element names inside parenthesis, in double quotes, separated by commas. For example: $(“div, p, h2”) this will select all the div, p and h2 elements of a page.

How do you select multiple elements *?

Selecting multiple elements To select multiple elements, you can simply click and drag your cursor over your them. Alternatively, hold down the Ctrl / Shift key on your keyboard (Cmd key for Mac) and click the elements to select them. Tip: You can select all elements at once by pressing Ctrl+A on your keyboard.

How do you select multiple elements in Javascript?

To select multiple elements, you can use the querySelectorAll() method. Just like the querySelector() method, you usually use it on the document object.


2 Answers

Problem with your approach

$(this, '#foo')

The above line will search for this inside an element with id set to foo, which isn't what you want here.


Solution

You can use add() for this :

var $el = $(this).add('#foo')

Now $el will contain $(this) & $("#foo") on which you can perform operations on.


More info on the methods used

add("selector")

  • Docs : http://api.jquery.com/add/
  • What it does : Add elements to the set of matched elements.
like image 81
krishwader Avatar answered Sep 28 '22 04:09

krishwader


The problem with the approach you're using:

$(this, '#foo')

JS Fiddle demo.

Is that this is a context-aware selection, searching for this within the #foo element (and is identical to $('#foo').find(this)), which is valid within jQuery, though I'd imagine somewhat pointless (given that you already have a reference to this (I assume, though if not this might be the window)).

In all honesty I'm not entirely sure why the selector 'works' at all, unless given the this node jQuery simply discards the context, given that it already 'knows' where the this node is and has a reference.

To add to a selection:

$(this).add('#foo');

JS Fiddle demo.

Or (conversely):

$('#foo').add(this);

JS Fiddle demo.

References:

  • add().
  • find().
  • jQuery selector-context.
like image 33
David Thomas Avatar answered Sep 28 '22 03:09

David Thomas