.style vs .className vs .setAttribute (v2)

Revision 2 of this benchmark created by Kyle A. Matheny on


Description

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

Preparation HTML

<style type="text/css">
 .hide {
   display:none;
 }
</style>

<div id="ctl00_ctl00_ctl00_LeftCol_leftNav">
        <ul>
            <li><a class="AspNet-Menu-Link" href="#">Home</a></li>
            <li><a class="AspNet-Menu-Link" href="#">Home &#38; me</a></li>
            <li><a class="AspNet-Menu-Link" href="#">home</a></li>
            <li><a class="AspNet-Menu-Link" href="#">Home > Apples</a></li>
            <li><a class="AspNet-Menu-Link" href="#">Home</a></li>
            <li><a class="AspNet-Menu-Link" href="#">Ho_me</a></li>
        </ul>
    </div>

Test runner

Ready to run.

Testing in
TestOps/sec
.style
var anchorElements = document.getElementById('ctl00_ctl00_ctl00_LeftCol_leftNav').getElementsByTagName('a'),
    anchorCount = anchorElements.length;

while (anchorCount--) {
 anchorElements[anchorCount].style.display = "none";
}
ready
.className
var anchorElements = document.getElementById('ctl00_ctl00_ctl00_LeftCol_leftNav').getElementsByTagName('a'),
    anchorCount = anchorElements.length;

while (anchorCount--) {
 anchorElements[anchorCount].className = "hide";
}
ready
.setAttribute
var anchorElements = document.getElementById('ctl00_ctl00_ctl00_LeftCol_leftNav').getElementsByTagName('a'),
    anchorCount = anchorElements.length;

while (anchorCount--) {
 anchorElements[anchorCount].setAttribute("class", "hide");
}
ready

Revisions

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