Home > Software engineering >  appendChild() Doesn’t Run When Using window.onload
appendChild() Doesn’t Run When Using window.onload

Time:07-23

I started learning javascript a few days ago and encountered this problem, I tried to figure it out on my own but I think it's about time I ask for some help. I was writing this script to add links to a bullet point list and appendChild() simply will not run using window.onload.

Here's my code, hopefully y'all can help me find out what's wrong with it:

function latestLinks() {
    const ul = document.getElementById("latest_links");
    const li1 = document.createElement("li");
    const li2 = document.createElement("li");
    const a1 = document.createElement("a");
    const a2 = document.createElement("a");
    const atext1 = document.createTextNode("About Me");
    const atext2 = document.createTextNode("My Blog");
    li1.appendChild(a1);
    li2.appendChild(a2);
    a1.appendChild(atext1);
    a2.appendChild(atext2);
    a1.setAttribute("href", "index.html")
    a2.setAttribute("href", "blog.html")
    ul.appendChild(li1);
    ul.appendChild(li2);
}

// This is the code that runs the functions on page load.

window.onload = function() {
    latestUpdate()
    latestLinks()
}

(PS: I've already tried the HTML attribute onl oad and that doesn't work either.)

CodePudding user response:

Use onload attribute on your body tag. body onl oad=“latestUpdate()” and then call latestlinks(); from latestUpdate(); window.onload will call when the window is loaded which will be before the body gets loaded which is where you’re tags are at.

I am almost positive if you were to open the console.log for your browser you would be getting an error because those scripts will not be loaded.

  • Related