2

i have some html and javascript, but the javascript only executes when I put it in an onclick. i am trying to just create a new list element.

dosent work:

<html>
<head>
<title></title>
<script type="text/javascript">

var newElement = document.createElement("li");
newElement.innerHTML = "hello";
var boo = document.getElementById("moo");
boo.appendChild(newElement);

</script>
</head>
<body>
<ul id="moo">
    <li>loo</li>
</ul>
</body>
</html>

does work:

<html>
<head>
<title></title>
<script type="text/javascript">
function hoo(){
var newElement = document.createElement("li");
newElement.innerHTML = "hello";
var boo = document.getElementById("moo");
boo.appendChild(newElement);
}
</script>
</head>
<body onclick="hoo()">
<ul id="moo">
    <li>loo</li>
</ul>
</body>
</html>

What am i doing wrong that doesn't let it execute on its own? Thanks in advance.

3 Answers3

3

The moment you load your script element with id=moo hasn't created yet. So var boo = document.getElementById("moo"); can't find any element. Try loading your script afte DOM is created.

In the second code your DOM has been created at the time you call the function so var boo = document.getElementById("moo"); can find the element and it is working as you expected.

For first code try:

<html>
<head>
<title></title>
</head>
<body>
<ul id="moo">
    <li>loo</li>
</ul>

<script type="text/javascript">

var newElement = document.createElement("li");
newElement.innerHTML = "hello";
var boo = document.getElementById("moo");
boo.appendChild(newElement);

</script>

</body>
</html>
laaposto
  • 11,835
  • 15
  • 54
  • 71
3

Your problem is caused by the fact you're executing the script at the top of the page. At that time the DOM is not yet parsed and the script will not be able to find the element with id moo.

Therefore, put the script at the bottom of the page:

<html>
<head>
<title></title>
</head>
<body>
<ul id="moo">
    <li>loo</li>
</ul>
</body>
<script type="text/javascript">

var newElement = document.createElement("li");
newElement.innerHTML = "hello";
var boo = document.getElementById("moo");
boo.appendChild(newElement);

</script>
</html>
thomaux
  • 19,133
  • 10
  • 76
  • 103
1

When Javascript tries to execute this line var boo = document.getElementById("moo"); the element with id="moo" does not exist yet. Try to move all your JS code before closing </body>