I’ve spent some time recently, thinking through an issue at work where I would need to create and update a list using plain Javascript due to some constrainst that I won’t go into at this time.
I’ve created the boilerplate HTML doc below just for the sake of demonstration:
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<link rel = "stylesheet" href = "stylesheet.css"
</head>
<body>
<container id="main">
<div>
<h1>
Enter a new list member:
</h1>
<form action="" id="getListMember" onsubmit="newMember(); return false;">
<label for="newListMember" id="newListMemberLabel">New Value</label>
<input type="text" id="newListMember" name="newListMember">
<input type="submit" value="Add"> <button type="button" onclick="delMember()">Remove
</button>
</form>
</div>
<div>
<ul id="newList">
</ul>
</div>
<div>
</div>
</container>
</body>
<script src=createNodeList.js></script>
</html>
I had to work through the order in which my specific new elements would be created. I basically wanted to create a list of items based off of submitted user input. However, I also wanted the items in the list to be individually selectable. This is so the user could select one or multiple items and delete them if needed.
The easiest way to acomplish this was with a checkbox appended to each list item. With checkboxes I would be able to add logic that would loop through the list and delete any items associated with a checked box.
First, I created the function newMember() that would create the new list items.
The new list item would receive a checkbox and then have the text appended in a text node. The text would come from the input field of a form (See my boilerplate HTML example above).
function newMember(){
var listForm = document.getElementById("getListMember") //Grab the form
var input1 = document.getElementById("newListMember").value; //Grab data from newListMember form field
var workingList = document.getElementById("newList"); //Grab the unordered list
var newListItem = document.createElement("li");
var newCheckBox = document.createElement("input");
newCheckBox.type = "checkbox";
newCheckBox.checked = false;
newCheckBox.name = "item";
newListItem.appendChild(newCheckBox);
newListItem.appendChild(document.createTextNode(input1));
workingList.appendChild(newListItem);
//Empty Form after submit
listForm.reset();
}
Next, I created the function delMember() which would be placed in the onclick attribute of the button that I would use to delete the selected list items.
function delMember(){
var cNode;
var nList = document.querySelectorAll("#newList li"); //Create a node list
for(var i=0; i < nList.length;i++){ //Loop through the list
cNode=nList[i].childNodes; //Get the child nodes array
x=cNode[0].checked; /* Select the input element at array position 0. and run a check to see if it is checked */
if(x==true){
nList[i].remove();
}
}
}
Well, I've got a solid starting point to build off of. This should be able to handle the bulk of the list related functionality!