JQuery multiplier with $ (this) selector

is there any way to make this work:

$(this, '#foo') 

with this i want to select the "this" and #bar element. Let’s say two identifiers for selection, it's as simple as '#foo, #bar' , but when I want one of these two to be “this”, I can’t get it to work.

+8
jquery this jquery-selectors getelementbyid multiple-instances
source share
3 answers

Problem with your approach

 $(this, '#foo') 

The above line will look for this inside the element with id set to foo , which is not suitable for you here.


Decision

You can use add() to do this:

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

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


Additional information on the methods used

add("selector")

+14
source share

The problem with the approach you are using:

 $(this, '#foo') 

JS Fiddle demo .

Is this a context-sensitive choice that looks for this in the #foo element (and is identical to $('#foo').find(this) ) that is valid in jQuery, although I would imagine a few pointless ones (given that you have there is already a link to this (I suppose, although if not this may be a window )).

Honestly, I'm not quite sure why the selector "works" at all, if this node is not set, jQuery just discards the context, given that it already "knows" where this node has and has a link.

To add to the selection:

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

JS Fiddle demo .

Or vice versa):

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

JS Fiddle demo .

Literature:

+4
source share

What you can also find is

 $('#foo', this) 

It will find the foo id object inside $(this)

+1
source share

All Articles