insertBefore method CODE
element.
insertBefore
(node1, node2) inserts
node1
as a child before
node2
JS
function myFunction() {
  // Creates new list item
  let newItem = document.createElement("li");
  newItem.innerHTML = "Water";
  
  // Puts list item into myList before "tea" item
  let list = document.getElementById("myList");
  list.insertBefore(newItem, document.getElementById("tea"));
}
HTML
<ul id="myList">
  <li>Coffee</li>
  <li id="tea">Tea</li>
  <li>Cocacola</li>
</ul>

<p>Click the button to insert an item to the list.</p>

<button onclick="myFunction()">Try it</button>
by Valeri Tandilashvili
4 years ago
JavaScript
DOM
3
Pro tip: use ```triple backticks around text``` to write in code fences