Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>why bother yourself guessing, here is a live example with the same structure and selectors: <a href="http://jsfiddle.net/3Ah5S/" rel="nofollow">http://jsfiddle.net/3Ah5S/</a></p> <p>HTML</p> <pre><code>&lt;div id="idP" class="classP"&gt; &lt;h1&gt;P&lt;/h1&gt; &lt;div id="idC1" class="classC1"&gt; &lt;b&gt;C1&lt;/b&gt; &lt;div id="idC11" class="classC11"&gt; --&gt;C11 &lt;/div&gt; &lt;div id="idC12" class="classC12"&gt; --&gt;C12 &lt;/div&gt; &lt;/div&gt; &lt;div id="idC2" class="classC2"&gt; &lt;b&gt;C2&lt;/b&gt; &lt;div id="idC21" class="classC21"&gt; --&gt;C21 &lt;/div&gt; &lt;div id="idC22" class="classC22"&gt; --&gt;C22 &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;br/&gt; &lt;div id="idResults"&gt; &lt;/div&gt; &lt;br/&gt; &lt;div id="classResults"&gt; &lt;/div&gt; </code></pre> <p>jquery test code</p> <pre><code>$(document).ready(function(){ startTime = new Date().getTime(); for (i = 0; i &lt; 10000; i++) { s = $("#idC12"); } $("#idResults").html("c12 by id time: "+elapsedMilliseconds(startTime)); startTime = new Date().getTime(); for (i = 0; i &lt; 10000; i++) { s = $(".classC12"); } $("#classResults").html("c12 by class time: "+elapsedMilliseconds(startTime)); }); function elapsedMilliseconds(startTime) { var n = new Date(); var s = n.getTime(); var diff = s - startTime; return diff; } </code></pre> <p>definitely ID time is faster cause it take advantage of browser-specific instructions to get your element directly without traversing the DOM tree.</p> <p><strong>Update:</strong> the reason why searching by ID is faster is that browsers tend to create a variable for every element with a unique ID inside your DOM tree while rendering the page, so querying by ID is the fastest way because it will get your element using the associated variable directly.</p> <p>a good explanation can be found here: <a href="http://javascript.info/tutorial/searching-elements-dom" rel="nofollow">http://javascript.info/tutorial/searching-elements-dom</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload