Search code examples
javascripthtmlpropertiesnullinnerhtml

Function wont find element from innerHTML


im doing a project on school, where we are making a website, and modularity was very important. therefore i put the header in innerHTML since it was going to be used on every page. i have a counter which use an element in that innerHTML, but when i call the counter it just says "Cannot set property of innerHTML of null. I've searched for hours but it dont seem to be any other who have had this exact problem.

The counter worked perfectly until i put the html in innerHTML.. I've laso tried to put the script both just under the header which the innerHTML is for, AND at the bottom, and under the body end-tag. all with the same result.

Here's the code for html and javascript. i've only taken with the lines that is used for this.

loadTop();
function loadTop() {
   document.getElementById("header").innerHTML = 
   '<div class="topbar">'+
       '<div class="cart">'+
           '<output type="number" id="orderCount">0</output>'
       '</div>'+
   '</div>';

  
}
       
window.onload = loadTop;
       
const cartNow = document.getElementById("orderCount");
let cartNum = 0;
 function cartCounter() {
    cartNum += 1;
    cartNow.innerHTML = cartNum;
    cartNow.style.opacity = 1;
    console.log(cartNow);
 }
<body>
        <header id="header"></header>
        <script src="script.js"></script>
        <button id="oatmeal" onclick="cartCounter()"> + </button>
</body>


Solution

  • You must call the JavaScript function at the beginning of your .js file, like this:

    loadTop();
    
    function loadTop() {
        document.getElementById("header").innerHTML =
            '<div class="topbar">' +
            '<div id="overskrift"><a href="index.html">ELEMENT</a></div>' +
    
            '<!--STJERNE-->' +
            '<div class="cart">' +
            '<output type="number" id="orderCount">0</output>'
    }
    
    const cartNow = document.getElementById("orderCount");
    let cartNum = 0;
    function cartCounter() {
        cartNum += 1;
        cartNow.innerHTML = cartNum;
        cartNow.style.opacity = 1;
        console.log(cartNow);
    }
    

    enter image description here