Jquery selectors

This post is about going through previously written code and looking at ways we can improve it, both the readability and the efficiency. Mostly these are little snippets of jQuery that perhaps don’t get noticed during a browse through the documents or are rarely useful. So, I’ll shut up and we’ll get started!

1. DON’T SELECT BY CLASS IF POSSIBLE.

Native Javascript contains two selectors: getElementById and getElementsbyTagName. You will notice there is no function to select elements by class. jQuery and most libraries do offer this function, and it’s not hard to write your own function to do it. However, due to it not existing natively, any custom function will be slower than using the two native functions above. So if you can avoid it, select elements by ID or by Tag Name over class where ever possible. Sometimes it is unavoidable of course, but if you can avoid it, do.

2. SAVE SELECTORS OR CHAIN ‘EM UP

See what’s wrong with this code?

 

$("div#elem").hide();

$("div#elem").css("width","200");

$("div#elem").show();

Nothing is exactly wrong. However a lot could be improved. Each time $(“div#elem”) appears, jQuery does a search through the DOM for it. In that snippet of code, jQuery has to search three times for the element. Why make it do all the work? Either chain the functions like so:

 

$("div#elem").hide().css("width","200").show();

Or save the element (also known as caching):

 

var myElement = $("div#elem");

myElement.hide();

myElement.css("width","200");

myElement.show();

Any element that you know you’re going to be referencing loads, save. However if you’re just using it in one block of code, I’d use chaining.

Caching also applies to the “this” keyword. Consider this loop:

 

$("div").each(function(i) {

$(this).addClass("myClass");

if($(this).hasClass("newClass") {

$(this).addClass("anotherClass");

}

});

While this might look all cosy, look how many times jQuery has to select the current element using $(this). This loop is much better:

 

$("div").each(function(i) {

var $this = $(this);

$this.addClass("myClass");

if($this.hasClass("newClass") {

$this.addClass("anotherClass");

}

});

When saving $(this) to a variable, I always name that variable $this, adding the dollar symbol at the beginning. This is because I can’t call a variable “this” as it’s a reserved word.

3. CONTEXTUAL INFORMATION

If you can provide extra information about the location of an element in the DOM, do. For example:

 

$(".myElem")

Will work fine, however if you can do this:

 

$("div.myElem")

This tells jQuery that the item with the class “myElem” must be within a div. So jQuery can use getElementsByTagName first to narrow down the search.

If you’ve already cached an element (see Tip 2) then you can actually add it as a second parameter when selecting another element:

 

$(".myElem", elementYouCachedInAVariable);

This tells jQuery to search for items with a class of “myElem” from within the cached element, again shortening the amount of work jQuery has to do.

4. AVOID EXTRA TRAVERSING

The most common example of this is as follows:

 

$("elem").find("p").hide().parent.find("h2").hide();

What happens here is we find paragraphs within an element, hide it, then select those paragraph’s parent again, then find any h2 elements within that element, then hide it. What’s wrong? We start at the parent level, then find paragraphs within it, but then go back up to parent level to find the h2s within the parent. Why not use the siblings function?

 

$("elem").find("p).hide().siblings("h2").hide()

But this can be even further improved, as the find() function can take multiple selectors:

 

$("elem").find("p, h2").hide();

Take a look at the original code and what we have now. Much nicer!

5. MAKE USE OF ANDSELF()

Rarely used as much as it should, andSelf() is useful for chaining the previous selection. For example, take code such as this:

 

$("div").find("p").addClass("myClass").parent().addClass("myClass");

That would seem the only logical way to do things. But no! Check this out:

 

$("div").find("p").andSelf().addClass("myClass");

Which again, saves us repeating the addClass() function and generally is nicer to look at.

If you have any questions, please leave a comment or grab me on Twitter: @Jack_Franklin.

 

http://www.thewebsqueeze.com/web-design-tutorials/improve-your-jquery-selectors-5-quick-tips.html

Leave a comment