Yeah, as Klaus mentioned, it is a tiny bit faster if you leave out the
'img'.

The real optimization you can do is to avoid using the same selector
repeatedly. In a way, jQuery makes it too easy to write inefficient code:

   $('#foo').doSomething();
   // ...later...
   $('#foo').doSomethingElse();

Replace that with:

   var $foo = $('#foo');
   $foo.doSomething();
   // ...later...
   $foo.doSomethingElse();

As you can see, I use $variableName as a convention to remind me that the
variable is a jQuery object.

This will make more of a difference with slower selectors like
$('.someClass'). Even though jQuery is much faster than it used to be, it's
still faster if you can avoid repeating the selector query at all.

-Mike

> From: NeilM
> 
> I have just started to use jQuery in my web development and 
> have a question concerning optimising element selection.
> 
> I find that I create a lot of references to id'd elements:
> 
> <img id="myImage" src="todaysimage.gif" width="20" height="20" />
> 
> Then, in my JavaScript, I want to obtain a reference to the element.
> Now, even though it has an id, I tend to use the full CSS 
> descriptor as, to me anyway, it makes the code more readable:
> 
> $("img#myImage").addClass("border");
> 
> My question is, apart from the overhead of some extra 
> characters in the script (e.g. 'img#'), does this style of 
> specification introduce a performance overhead internally 
> within jQuery? Would/does jQuery optimise the element 
> selection process if it just 'sees' a simple id string 
> starting with a #?
> 
> $("#myImage").addClass("border");

Reply via email to