views:

154

answers:

3

Hi,

$('#content td#foo').show();
$('td#foo').show();

The td is somewhere deep in the content div.

What is faster?

+14  A: 

You can simply write

$("#foo").show();

You cannot have more than 1 elements with the same id. So no need to use any additional selector to get an element with a particular id. So your td tag selector can be avoided.

rahul
Is that an "S" in front?
fudgey
Thx guys for the quick help! :-)
christianhaller
Fixed the typo. Thanks @fudgey
rahul
+8  A: 

Both of those selectors will resolve to:

$('#foo').show();

however, the manual says:

For id selectors, jQuery uses the JavaScript function document.getElementById(), which is extremely efficient. When another selector is attached to the id selector, such as h2#pageTitle, jQuery performs an additional check before identifying the element as a match.

You can think of the aforementioned additional check as completely pointless, unless you have duplicate IDs in your markup, which is incorrect in terms of the definition and usage of the HTML ID attribute. See http://www.w3schools.com/tags/att_standard_id.asp.

karim79
+14  A: 

The fastest is:

$('#foo').show();

IDs must be unique, this results in a hash table lookup in the browser for the reference to the DOM element, doesn't get any faster than that. If your ID foo isn't unique, you have other problems...that is invalid HTML.

Nick Craver