Javascript and the DOM: innerHTML, createElement and appendChild

Let's suppose first of all that we have a simple list and a button, and when we press the button we want to change the contents of the first list item. Here's the HTML of the list and the button
<html>
<button onclick="changeItemOne();">Change List Item 1</button>
<ul>
<li id="listItemOne">List Item 1</li>
<li id="listItemTwo">List Item 2</li></ul>

</html>
and inside the function is a single line of code.
<script> 
function changeItemOne() {
//change the inner HTML of the element
document.getElementById("listItemOne").innerHTML="You changed me";
}
</script>
The whole thing looks like this:
<html>
<script> 
function changeItemOne() {
//create the inner HTML of the element
document.getElementById("listItemOne").innerHTML="You changed me";

}
</script>
<button onclick="changeItemOne();">Change List Item 1</button>
<ul>
<li id="listItemOne">List Item 1</li>
<li id="listItemTwo">List Item 2</li></ul>

</html>
But suppose we don't want to change something but to create something. If this is the case then we might use createElement and appendChild alongside innerHTML as shown in the below example.
<html>
<script> 
//establish a value for the variable i
var i=1;
//create the function that is going to be triggered when the button is pressed
function newNode() {
//define the listItem, i.e. a new list element
var listItem = document.createElement("li");
//create the inner HTML of the element
listItem.innerHTML="List Item " + i;
//locate where the item is to be added in the DOM and add it so that it displays in the browser
document.getElementById("list").appendChild(listItem);
//Update the value of the variable being used so we can see this has increased
i++;

}
</script>
<button onclick="newNode();">Add List Item</button>
<ul id="list"></ul>

</html>

Comments