Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does jQuery re-query the DOM when $(this) is called?

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?
});
like image 438
monners Avatar asked Jan 18 '14 04:01

monners


People also ask

What does $( this mean in jQuery?

$(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.

When we should use $( this in jQuery?

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.

What do jQuery selectors return?

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 correct about $( this in jQuery?

Which is the correct jQuery selector to select current HTML element? Explanation: The $(this) selector is used to select current HTML elements. 19.


1 Answers

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.

like image 173
elclanrs Avatar answered Sep 18 '22 14:09

elclanrs