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
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'));
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.
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