x
1
2
<html>
3
<body>
4
5
<ul id="myList">
6
<li>Coffee</li>
7
<li>Tea</li>
8
</ul>
9
10
<p>Click the button to insert an item to the list.</p>
11
12
<button onclick="myFunction()">Try it</button>
13
14
<p><strong>Example explained:</strong><br>First create a LI node,<br> then create a Text node,<br> then append the Text node to the LI node.<br>Finally insert the LI node before the first child node in the list.</p>
15
16
<script>
17
function myFunction() {
18
var newItem = document.createElement("LI");
19
var textnode = document.createTextNode("Water");
20
newItem.appendChild(textnode);
21
22
var list = document.getElementById("myList");
23
list.insertBefore(newItem, list.childNodes[0]);
24
}
25
</script>
26
27
</body>
28
</html>