.style vs .className vs .setAttribute (v8)

Revision 8 of this benchmark created on


Description

Is it faster to use JavaScript .style, or to change the class of an object using .className?

Edit Note: The original test case was not general enough. Hiding an element is just one side of the story, you should be able to make it visible again. Also you may want to hide an element which already has a class, you need a bit more complex logic in this case. Finally, setAttribute("class", ...) doesn't work in IE, it needs className instead.

Conclusion: Setting style directly wins in IE 6-7, Opera. No noticable difference in all other browsers.

Preparation HTML

<style type="text/css">
  .hideDiv{ display:none; } .showDiv {display:block;}
</style>
<div>
        <ul>
                <li><a onclick="tabview('show_layer1');">tab1 navi</a></li>
                <li><a onclick="tabview('show_layer2');">layer 2</a></li>
                <li><a onclick="tabview('show_layer3');">layer 3</a></li>
                <li><a onclick="tabview('show_layer4');">layer 4</a></li>
                <li><a onclick="tabview('show_layer5');">layer 5</a></li>
                <li><a onclick="tabview('show_layer6');">layer 6</a></li>
        </ul>
</div>
<div id="show_layer1" style="top:50px; left:100px;" class="hideDiv">tab1</div>
<div id="show_layer2" style="top:90px; left:100px;" class="hideDiv">layer 2</div>
<div id="show_layer3" style="top:130px; left:100px;" class="hideDiv">layer 3</div>
<div id="show_layer4" style="top:180px; left:100px;" class="hideDiv">layer 4</div>
<div id="show_layer5" style="top:210px; left:100px;" class="hideDiv">layer 5</div>
<div id="show_layer6" style="top:250px; left:100px;" class="hideDiv">layer 6</div>

<script>
var oldDiv = '';
  function tabview(targetid) {
   document.getElementById(targetid).className = 'showDiv';
   if (oldDiv != '') {
    document.getElementById(oldDiv).className = 'hideDiv';
    document.getElementById(targetid).className = 'showDiv';
   }
   oldDiv = targetid;
   }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
.style
var oldDiv = '';
  function tabview(targetid) {
   document.getElementById(targetid).style.display = 'block';
   if (oldDiv != '') {
    document.getElementById(targetid).style.display = 'none';
    document.getElementById(targetid).style.display = 'block';
   }
   oldDiv = targetid;
   }
ready
.className
var oldDiv = '';
  function tabview(targetid) {
   document.getElementById(targetid).className = 'showDiv';
   if (oldDiv != '') {
    document.getElementById(oldDiv).className = 'hideDiv';
    document.getElementById(targetid).className = 'showDiv';
   }
   oldDiv = targetid;
   }
 
ready

Revisions

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