views:

132

answers:

3

I came across Google's Page Speed add-on for Firebug yesterday. The page about using efficient CSS selectors said to not use overqualified selectors, i.e. use #foo instead of div#foo. I thought the latter would be faster but Google's saying otherwise, and who am I to go against that?

So that got me wondering if the same applied to jQuery selectors. This page I found the link to on SO says I should use $("div#foo"), which is what I was doing all along, since I thought that things would speed up by limiting the selector to match div elements only. But is it really better than writing $("#foo") like Google's saying for CSS selectors, or do CSS versus jQuery element matching work in different ways and I should stick with $("div#foo")?

+4  A: 

$("#foo") is better than $("div#foo")

Since id is unique in the document you don't have to prefix it with a tag name.

Here is a nice link

jQuery Performance Rules

rahul
Thanks. So it's #foo instead of div#foo. The page also mentions using div.foo instead of just .foo. Does it apply to CSS as well then?
Moss
+1  A: 

The Sizzle Selector Engine parses selectors right to left.

Use IDs as much as you can to enhance performance.

Jacob Relkin
+1  A: 

The more specific the selector is, the faster Sizzle (jQuerie's selector engine) finds that object.

Reason: getElementsByTagName is used to narrow the search down to a few cases.

But this doesn't apply on unique id-names!

Labuschin