Javascript code not running

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

<ul id="ul">
	<li>One	</li>
	<li>Two </li>
	<li>Three </li>
	<li>Four </li>
	<li>Five </li>
	<li>Six </li>

</ul>
var ul=document.getElementById("ul");
var element=document.createElement("li");
var text=document.createTextNode("Seven");
element.appendChild(text);
ul.appendChild(element);

P.S javascript is in external file

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.

1 Like

No, there is probably something fishy with jsfiddle. :wonky:

Always do your final testing in a reliable browser. :winky:

coothead

1 Like

I moved it down. Mistakenly I placed it after the opening body tag. Problem is solved thanks

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.

<body>
    ...
    <script src="..."></script>
</body>
</html>

One unpleasant whiff is more than enough for me. :wonky:

Call me a “stick-in-the-mud”, if you wish, but I will carry on
doing what I have always done ; test code in my browser. :winky:

coothead

The only benefit I find from jsfiddle is that I don’t end up with .html files scattered all over the place.

Well that takes a lot of time :banghead:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.