2

The javascript code is here:

function hidepre() {
    var pre = this.getElementsByTagName("pre")[0]
    if (pre.style.display === "none") {
        pre.style.display = "block";
    } else {
        pre.style.display = "none";
    }
}
function hidepreall() {
    var prewraps = document.getElementsByClassName("prewrap");
    if(prewraps.length > 0) {
        for (var i = 0; i < prewraps.length; i++) {
            var prewrap = prewraps[i];
            prewrap.onclick = hidepre;
        }
    }
}
window.onload = hidepreall;

This works fine in my firefox, but if I use the for(var i in obj) form, like this

    for (var prewrap in prewraps) {
        prewrap.onclick = hidepre;
    }

it stops working.

http://jsfiddle.net/5DmuE/1/ http://jsfiddle.net/5DmuE/2/

Both fiddles are not working in both cases.

qed
  • 22,298
  • 21
  • 125
  • 196

1 Answers1

2

The for-in loop is not for looping through entries in arrays or array-like things (what you get back from getElementsByClassName is an array-like object called a NodeList). It's for looping through the enumerable names of properties of an object. Using for-in on a host-provided object (like a NodeList) is not guaranteed to work.

Use a nice simple for loop, or convert the NodeList into an array and use forEach on it (you can shim forEach on the few remaining browsers that don't have it). Here's an example:

Array.prototype.slice.call(prewraps, 0).forEach(function(element) {
    // ...use the element here
});

(The slice thing is a convenient way to create an array out of any array-like object.)

More about looping through arrays in this answer.

More about for-in on my blog: Myths and realities of for-in

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875