Search code examples
javascriptinnerhtml

One javascript function disables other functions


I have 3 functions:

window.onload = function() {       
    canvas();   
    changeColor();
    blockSize();    
}

The problem is with third "blockSize()". It not running when I place it at the bottom of window.onlod function; + when I place it at the top, it disables all functions below it. Here is the code (calculates width and height in percentages of all blocks with className "size"):

function blockSize() {
    var block = document.getElementsByClassName("size");    
    for (var i in block) {       
        var width = Math.round(block[i].clientWidth/document.documentElement.clientWidth*100);
        var height = Math.round(block[i].clientHeight/document.documentElement.clientHeight*100);
        var span = document.createElement("span");
        span.innerHTML = width+"x"+height+"%";
        block[i].appendChild(span);
    }    
}

Noticed, that problem appers when I appendChild (last line). When I remove it, other functions works properly. Also tried to put < span> manually inside a div and use this javascript line instead (same results):

block[i].firstChild.innerHTML = width+"x"+height+"%";

!!! When I use only innerHTML, everything works fine. And I understand, that I can use something like this, and it will work:

block[i].innerHTML = "<span>"+width+"x"+height+"</span>";

Solution

  • The problem most likely comes from improperly using for-in on an HTMLCollection. This will include other items besides DOM elements.

    when it encounters the block[i].appendChild(span), it'll throw an error if block[i] isn't an element and therefore doesn't have an .appendChild() method.

    Use a for loop instead.

    function blockSize() {
        var block = document.getElementsByClassName("size");    
        for (var i = 0; i < block.length; i++) {       
            var width = Math.round(block[i].clientWidth/document.documentElement.clientWidth*100);
            var height = Math.round(block[i].clientHeight/document.documentElement.clientHeight*100);
            var span = document.createElement("span");
            span.innerHTML = width+"x"+height+"%";
            block[i].appendChild(span);
        }    
    }