Home > Software engineering >  Adding h1 element using JavaScript is not working
Adding h1 element using JavaScript is not working

Time:04-10

I am trying to write a simple view function that inserts text into the content div. Call this view function in the redraw function. Set window.onload to the redraw function so that it is called when the page has finished loading. However, I can't seem to get it working. I am wondering what the problem is? Here is my JavaScript code:

 // redraw is called whenever the page needs to be 
// updated, it calls the appropriate view function
const redraw = () => {
}

//create the view function
function view(){
    //get the id of the div and change its inner HTML
    document.getElementById("content").innerHTML = "<h1>Lorem Ipsum</h1>";
    }
//make the redraw function to call the view function
function redraw(){
    view();
    
}
//load the redraw function whenever the webpage will be reload
window.onload= redraw();

CodePudding user response:

You declared the redraw twice, Also - You should run the code after content loaded.

This is a working code:

    //create the view function
    function view(){
        //get the id of the div and change its inner HTML
        document.getElementById("content").innerHTML = "<h1>Lorem Ipsum</h1>";
        }
    //make the redraw function to call the view function
    function redraw(){
        view();
        
    }
    //load the redraw function whenever the webpage will be reload
    //window.onload= redraw();
    document.addEventListener("DOMContentLoaded", redraw);

CodePudding user response:

You actual made two redraw first in top and then in the bottom hope the below code helps:

function view(){
    document.querySelector("#content").innerHTML = "<h1>Lorem Ipsum</h1>";
}

function redraw(){
    // You made this function two times.
    view();
}

window.onload= redraw;
<!doctype HTML>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
      <div id="content"> </div>
    </body>
</html>

  • Related