Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A jQuery question about variables and selectors

Lately, I have been doing this in an effort to speed up performance (and sometimes it helps with maintainability)

var objectToReference = $('div .complicated #selector ul:last');

So what does objectToReference really hold? Sometimes things have bitten me, so I've gone back to using the full selector and it has worked.

So does the variable hold a reference, a pointer, etc (I'm not sure the exact definition of those terms)

Thanks

like image 725
alex Avatar asked Jun 02 '09 01:06

alex


2 Answers

A best practice that many people use when they create a variable like this is to name it starting with $, to indicate that it is a jquery object. So you could name the variable $o, and you can directly call other jQuery chain functions after it, without having to put $() around the variable.

$o.hide();

It is a good idea to start with the surrounding element for the area you are manipulating, to avoid having to search the entire document. For example, to get all links within a single section of the document (without having to search the whole document):

var $o = $('#mysection');
var $links = $('a', $o); // equiv to $o.find('a')

Finally, it never hurts to pass a jQuery object back through jQuery:

$o === $($o)

This has a nice side effect - you can write a function that accepts any of the following as an argument: a selector, an element, or a jQuery object:

function myFunc(e) {
    var $e = $(e);
}
// All of the following will work:
myFunc('#mysection');
myFunc(document.getElementById('mysection'));
myFunc($('#mysection a'));
like image 74
BarelyFitz Avatar answered Oct 14 '22 09:10

BarelyFitz


The return value of a jQuery selector is an array of jQuery elements. If the selector does not find any matches, then it contains an array with 0 elements.

Each element in the array is essentially a reference to the matching DOM element in the HTML document. This is what allows you to traverse and manipulate them as needed.

like image 39
Jose Basilio Avatar answered Oct 14 '22 09:10

Jose Basilio