JSFiddle - React, Tailwind, and code Playground
HTML
First name:
<input type="text" id="firstname">
<br>
<p>Your first name is: <b id='boldStuff2'></b>
</p>
<p>Other people's names:</p>
<ol id="demo"></ol>
<input type='button' onclick='changeText2()' value='Submit' />
<input type='button' onclick='alert(getNames())' value='Alert Names' />
JavaScript
var list = document.getElementById('demo');
var names = []; // [] is same as new Array();
function changeText2() {
var firstname = document.getElementById('firstname').value;
document.getElementById('boldStuff2').innerHTML = firstname;
names.push(firstname);//simply add new name to array;
//array changed re-render list
renderList();
}
function renderList(){
/* simply doing
* list.innerHTML = ""
* would also work, but below code performs much faster
*/
//clean the list
while (list.firstChild) {
list.removeChild(list.firstChild);
}
//create each li again
for(var i=0;i<names.length;i++){
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(names[i]));
var removeButton = document.createElement('button');
removeButton.appendChild(document.createTextNode("remove"));
removeButton.setAttribute('onClick','removeName('+i+')');
entry.appendChild(removeButton);
list.appendChild(entry);
}
}
function removeName(nameindex){
names.splice(nameindex,1);
//array changed re-render list
renderList();
}
function getNames(){
return names;
}