fastest way to check if a container has any content

JavaScript performance comparison

Revision 4 of this test case created by Kyle Farris

Info

Most use $(element).children().length > 0 but I wonder if there's a much faster way if you just have to check for any content to be present.

Preparation code

<ul id="container">
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
<li><a href=“#“></a></li>
</ul>
<script src="//cdnjs.cloudflare.com/ajax/libs/sizzle/1.10.19/sizzle.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
Benchmark.prototype.setup = function() {
    var container = document.getElementById('container');
    var $container = $(container);
    var $$container = Sizzle('#container');
};
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Common jQuery way
$container.children().length > 0;
pending…
pure JS way
container.childNodes.length > 0;
pending…
jQuery check for first only
$container.children('first-child').length > 0;
pending…
js check for first only
container.firstChild.length > 0;
pending…
jQuery check content string
$container.html().length > 0;
pending…
js check content string
container.innerHTML.length > 0;
pending…
Check if is parent
$container.is(':parent');
pending…
Work off jQuery Object if you already have it...
$container[0].firstChild.length > 0;
pending…
Sizzle Way
Sizzle('> *',$$container).length > 0;
pending…
Another jQuery Way
$container.find('> *').length > 0;
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:

0 comments

Add a comment