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.
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.
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.
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.
To select multiple elements, you can use the querySelectorAll() method. Just like the querySelector() method, you usually use it on the document object.
$(this, '#foo')
The above line will search for this
inside an element with id
set to foo
, which isn't what you want here.
You can use add()
for this :
var $el = $(this).add('#foo')
Now $el
will contain $(this)
& $("#foo")
on which you can perform operations on.
add("selector")
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()
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With