JSFiddle - React, Tailwind, and code Playground
HTML
<div id="container">
<h3>My Favorite Colors!</h3>
<p id="demo">Click the button to insert a color into the list</p>
<ul id="colors">
<li id="Red">Red</li>
<li id="Blue">Blue</li>
</ul>
</div>
<button onclick="addChildToTop()"> Adding Node</button>
<button onclick="removeColor()"> Removing Node</button>
JavaScript
function addChildToTop() {
var oldcrayon = "nocolor"
var crayon = prompt("Please enter a color")
if (crayon === null || crayon === oldcrayon || crayon === "") {
// cancel button was hit
// or the same value was entered
//nothing is empty
return false;
}
var newItem = document.createElement("LI");
newItem.id = crayon // so it can be referenced for removal
// Note: ids _should_ be unique and we're not doing anything to validate
// that. For example, what if someone adds Red twice? Then there'd be
// to elements with the id "Red"
var textnode = document.createTextNode(crayon);
newItem.appendChild(textnode);
var list = document.getElementById("colors");
list.insertBefore(newItem, list.childNodes[0]);
}
function removeColor() {
var crayon = prompt("Enter a color to remove from list");
// Get the item with the id matching the user input
removeItem = document.getElementById(crayon);
// if the id wasn't found, removeItem will be null. We also check
// to make sure the found item is in the colors list and not matching
// an id somewhere else in the document.
if (removeItem && document.getElementById("colors").contains(removeItem)) {
removeItem.parentNode.removeChild(removeItem);
}
}