getElementById
is returning null when assigned to a variable.
var element = document.getElementById("ul1");
var newelement = document.createElement("li");
newelement.innerHTML = "New";
element.appendChild(newelement);
getElementById
is returning null when assigned to a variable.
var element = document.getElementById("ul1");
var newelement = document.createElement("li");
newelement.innerHTML = "New";
element.appendChild(newelement);
When you put your javascript in the head
of the document it will load (and block the loading of the body
) before any other element on the page.
A quick example of what you're actually doing would be this:
<!-- script runs before element creation -->
<script type="text/javascript">
var element = document.getElementById('ul1');
</script>
<!-- this is after execution, where JS could not find the element but only now is the element actually created -->
<ul id="ul1"></ul>
To solve this issue, you can do a few things
<script>
tag below the element you want to target<script>
tag just above the closing </body>
tag)window.onload = function() { ... }
to make sure the page is loaded before doing anything.Then the ul
element will exist and you will be able to append your LI :)
`. It's cleaner and takes advantage of caching.
– abluejelly Dec 08 '15 at 17:23