I want to add elements to DOM using javascript. It’s giving error in my browser console.TypeError: Cannot read property ‘appendChild’ of null but it works fine on jsfiddle. Is there something fishy with my browser? Here is the simple code
var ul=document.getElementById("ul");
var element=document.createElement("li");
var text=document.createTextNode("Seven");
element.appendChild(text);
ul.appendChild(element);
Where in the HTML body is the script tag that loads the external code?
If it’s before or at the start of the body, the rest of the page content won’t exist yet.
Move the script down to the end of the body, and that will fix the problem.
The only thing fishy is that jsfiddle defaults to a load type of onload, which wraps your code and delays it until the page has fully loaded.
window.onload = function () {
// code in here
};
The problem there though is that anything else using the onload handler will replace your code, so you end up having to use addEventListener, or addEvent with older IE browsers.
Other issues with onload are that it waits until all pictures and page content have finished loading, which in some circumstances can take quite some time.
Due to that and other problems, placing scripts at the end of the body, or “No wrap ” as jsfiddle calls it, is the best solution overall.