JQuery selector - which is faster?

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

td is somewhere deep in the content div.

Which is faster?

+6
jquery jquery-selectors
source share
3 answers

You can just write

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

You cannot have more than one item with the same identifier. Therefore, there is no need to use an additional selector to get an element with a specific identifier. Therefore, you can avoid selecting tag tags.

+16
source share

The fastest of them:

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

The identifiers must be unique, this leads to the fact that the search in the hash table in the browser to refer to the DOM element is not accelerated. If your foo id is not unique, then you have other problems ... this is invalid HTML.

+16
source share

Both of these selectors will allow:

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

however, management says:

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

You can think of the above additional verification as completely pointless if you don't have duplicate identifiers in your markup, which is wrong in terms of defining and using the HTML ID attribute. See http://www.w3schools.com/tags/att_standard_id.asp .

+8
source share

All Articles