In the following code, when $(this)
is called, does jQuery re-query the DOM as though a selector has been passed to it (using some property of the object as a selector), or does jQuery retain the previously returned object?
$('.someButton').on('click', function() {
$(this).remove(); // Is this another lookup, or just a wrapper for the previously returned object?
});
$(this) is a jQuery wrapper around that element that enables usage of jQuery methods. jQuery calls the callback using apply() to bind this . Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.
this would refer to the current DOM element h1 which invoked the event. Enclosing it with a $ makes it a jquery object. So $(this) basically refers to the jquery h1 object . So $(this) = $('h1') where h1 is the event which triggered the event.
The jQuery Object: The Wrapped Set: Selectors return a jQuery object known as the "wrapped set," which is an array-like structure that contains all the selected DOM elements. You can iterate over the wrapped set like an array or access individual elements via the indexer ($(sel)[0] for example).
Which is the correct jQuery selector to select current HTML element? Explanation: The $(this) selector is used to select current HTML elements. 19.
It doesn't re-query the DOM, this
is already an element. jQuery simply sets the context to the element, adjusts the length, and returns itself. This code is from the init
function, which runs when you do $(something)
, this is part of a big if..else
statement, where it also checks for selectors, arrays among other things:
// HANDLE: $(DOMElement)
} else if (selector.nodeType) {
this.context = this[0] = selector;
this.length = 1;
return this;
So basically it just wraps the element in a new jQuery object.
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