I need help understanding $(this)
. Is it possible to narrow the focus of "this" within the parentheses or does "this" preclude the use of any other attributes?
For example: I don't understand why this code:
$(this).children("div")
can't be rewritten like this:
$(this + " div")
without having to resort to something like:
$('#'+$(this).attr("id")+ " div")
Also, can you point me to 'this' in the jQuery documentation? It is difficult to use 'this' as a search term for obvious reasons.
$(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.
$ is pretty commonly used as a selector function in JS. In jQuery the $ function does much more than select things though. You can pass it a selector to get a collection of matching elements from the DOM. You can pass it a function to run when the document is ready (similar to body.
Use .find()
$( this ).find( 'div' )
Or use the context
parameter to jQuery( selector, context )
(internally, it just calls find anyway...)
$( 'div', this )
this
isn't a jQuery "thing", but a basic JavaScript one. It can't be re-written the way you have in examples because it's an object, in particular either a DOM element or a jQuery object (depending on what context you're in). So if you did this:
$(this + " div")
What you'd really be doing is calling .toString()
on this
to concatenate the strings, resulting in:
$("[object Object] div")
....which isn't a valid selector.
As for further reading, I believe this article continues to be one of the best references/resources to learn what this
(a context keyword) means.
Per comment requests, some examples of what this
is in various places:
$("selector").click(function() { alert(this); });
this
refers to the DOM element the event handler is being triggered on.$.fn.myPlugin = function() { alert(this); });
this
is the jQuery object the plugin was called/chained on, for example: $("selector").myPlugin();
, this
is that $("selector")
jQuery object.function myFunc() { alert(this); };
this
is the context you're in, whether it be an object or something else, a few examples:$("selector").click(myFunc);
- this
is the DOM element, like above$("selector").click(function() { myFunc(); });
- this
is the global content, window
myFunc.call(whatThisIs, arg1, arg2);
- this
is whatThisIs
Function.call()
and Function.apply()
for more infoIf 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