Search code examples
javascriptjqueryhtmlvariablesonload

OnLoad Only Called Once With Document.getElementById


In my JS file, I'm trying to create a list from a JavaScript array. Obviously, you can't do document.getElementId before the page has loaded since the JS is called first. The if statement produces three results, but only one is loaded because of the window.onload function.

var getDateContent = function(year,month,date){         
    if(contentObj != null && contentObj[year] != null && 
        contentObj[year][month] != null && 
        contentObj[year][month][date] != null){

        var contentObjArray = contentObj[year][month][date];
        window.onload=function(){
            var items = document.getElementById("test");
            for (var i = 0; i < contentObjArray.length; i++ ) {
                var item = document.createElement("li");
                item.innerHTML = contentObjArray[i];
                items.appendChild(item);
            }
        }
    }  
}

I guess my question is, how can I access the element id without window.onload? This is because window.onload only runs once when I need it to run multiple times


Solution

  • Use addEventListener instead of assigning to the onload property.

    addEventListener('load', function () { /* ... */ });
    

    This will just add additional listeners instead of overwriting the previous one.

    (You need a shiv for IE8)