10

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.

Lukáš Řádek
  • 1,014
  • 1
  • 9
  • 18

3 Answers3

18

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")

krishwader
  • 11,141
  • 1
  • 32
  • 51
  • 1
    Thank you. I knew my sample code was not working and I thought it was selecting rather #foo inside this. So this is a little surprise, that it work vice versa.And I put it here that way, because it felt to me the closest to the multiple IDs selection. – Lukáš Řádek Jul 06 '13 at 20:05
4

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:

David says reinstate Monica
  • 230,743
  • 47
  • 350
  • 385
1

What you may also be looking for is

$('#foo', this)

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

depperm
  • 8,490
  • 4
  • 37
  • 57
user875479
  • 125
  • 7