JavaScript: DOM getElementByID

Example: JavaScript: Using DOM getElementByID to Create a Dynamic HTML List

This JavaScript will allow a user to enter text into an HTML input box and then click a button to add this text to an HTML unordered (bulletted) list dynamically (on-the-fly).


	<head>
	<meta charset="UTF-8">
	<title>HTML DOM getElementById</title>
	<script>
	function addItem(){
		var ul = document.getElementById("dynamic-list");
		var candidate = document.getElementById("candidate");
		var li = document.createElement("li");
		li.setAttribute('id',candidate.value);
		li.appendChild(document.createTextNode(candidate.value));
		ul.appendChild(li);
	}

	function removeItem(){
		var ul = document.getElementById("dynamic-list");
		var candidate = document.getElementById("candidate");
		var item = document.getElementById(candidate.value);
		ul.removeChild(item);
	}
	</script>
	</head>
	<body>

		<p>Enter text into textbox and click Add button to add it to the list.</p>
	
		<ul id="dynamic-list"></ul>

		<input type="text" id="candidate">
		<button onclick="addItem()">Add Item</button>
		<button onclick="removeItem()">Delete Item</button>

		<script src="script.js"></script>
	

Run It