jQuery context or no context

JavaScript performance comparison

Test case created by Zander Martineau

Info

Test to understand better selector performance in jQuery

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<div id="parent">
  <div class="a">
    a
  </div>
  <div class="a">
    a
  </div>
  <div class="a">
    a
  </div>
  <div class="a">
    a
  </div>
  <div class="a">
    a
  </div>
  <div class="a">
    a
  </div>
  <div class="a">
    a
  </div>
  <div class="a">
    a
  </div>
  <div class="a">
    a
  </div>
</div>

Preparation code output

a
a
a
a
a
a
a
a
a

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
With context
$('.a', '#parent').css({
  border: '1px solid red'
});
pending…
Without context
$('#parent .a').css({
  border: '1px solid blue'
});
pending…
Without context, but only select the child
$('.a').css({
  border: '1px solid pink'
});
pending…
Without context, selecting the child & give node specificity
$('div.a').css({
  border: '1px solid green'
});
pending…
Create variable for the id then use that in context
var context = document.getElementById('parent');

$('.a', context).css({
  border: '1px solid gray'
});
pending…
Do the same as the last but use jQuery to find the the element
var context = $('#parent');

$('.a', context).css({
  border: '1px solid yellow'
});
pending…
Use jQuery .find
$('#parent').find('.a').css({
  border: '1px solid purple'
});
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

1 comment

alireza balouch commented :

Hi can you add

$('#parent > .a').css({ border: '1px solid blue' });

and this on

$('#parent > div.a').css({ border: '1px solid blue' });

to this test.

Thanx ;)

Add a comment