Even when you have a basic understanding of when the this keyword points to a DOM element or to a jQuery object, the concept can still be confusing once you save the value of this to a variable. Imagine that you are working in a complex function and you don’t know whether your variable refers to a DOM element or a jQuery object. A common way to get around this confusion is to use a naming convention to help out. Here’s an example:
$('a').click(function() { var $anchor = $(this); $anchor.fadeOut(); })
As you can see in the example, I wrapped the DOM element from the callback function with a jQuery object and then stored the results in a variable whose name is prepended with a dollar sign ($). The $ symbol doesn’t have any special behavior, it is just a reminder to the reader that the variable refers to a jQuery object rather than to a DOM element.
There also might be occasions when you need the DOM element from a jQuery object. The following code snippets show several ways of obtaining the raw DOM element:
// Gets the collection of anchor tags from the jQuery array $('a').get(); // Various ways to get the 0th item in the jQuery array of DOM elements $('a').get()[0]; // Get method returning jQuery array and then indexing 0th item $('a').get(0); // Get method accessing DOM element at 0th index $('a')[0]; // Array accessor syntax getting the 0th indexed item
If you have not used a naming convention and you aren’t sure whether you are dealing with a jQuery object or a DOM element, you can use the following code snippet:
// Check if source is a jQuery object and contains one or more elements if (source instanceof jQuery && source.length > 0) { var element = source[0]; }