fastest way to check if a container has any content

JavaScript performance comparison

Test case created by Simon Harte

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="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
Benchmark.prototype.setup = function() {
    var container = document.getElementById('container'),
        $container = $(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…

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