SO question: 16137043

JavaScript performance comparison

Test case created by PeeHaa

Info

SO question: http://stackoverflow.com/questions/16137043/how-to-hide-element-with-dom-path-and-class-in-html-document

Preparation code

<div class="list first">
  <span class="total">2</span>
  <div class="object"></div>
</div>

<div class="list">
  <span class="total">7</span>
  <div class="object"></div>
</div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Preparation code output

2
7

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Vucko's answer
var text = []; // array to put all the span values in
$('.total').each(function(){  //putting the values of span one by one into the array
    text.push( $(this).text());
});

$.each(text,function(){ //looping through the array and if the array value is larger then 2 ,it trigger the if statment
    if(this>2){
        $('.first').hide();
    }
});
pending…
Ambrosia's answer 1
var divs = document.getElementsByTagName("div");
for(var i=0; i < divs.length; i++)
{
    if((" "+divs[i].className+" ").replace(/[\n\t\r]/g, " ").indexOf(" list ") > -1)
    {
        if((" "+divs[i].className+" ").replace(/[\n\t\r]/g, " ").indexOf(" first ") > -1)
        {
            var spans = divs[i].getElementsByTagName("span");
            for(var j = 0; j < spans.length; j++)
            {
                if((" " + spans[j].className +" ").replace(/[\n\t\r]/g, " ").indexOf(" total ") > -1)
                {
                    if(spans[j].innerHTML > 2)
                    {
                        spans[j].style.display = "none";
                    }
                }
            }
        }
    }
}
pending…
Ambrosia's answer 2
$('div.list.first .total').each(function()
{
    if($(this).text() > 2)
        $(this).parent().hide();
});
pending…
Jon P's answer
if($(".total").filter(function (){return $(this).text() >2; }).length > 0)
{
    $(".first").hide();
}
pending…
PeeHaa's answer
    var totals = document.querySelectorAll('.total');
    for (var i = 0, l = totals.length; i < l; i++) {
        if (totals[i].childNodes[0].nodeValue < 2) {
            continue;
        }
   
        document.querySelector('.first').style.display = 'none';
    }
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment