I was trying to create a to-do list where with help of one input tag I wanted to enter all todo lists by adding HTML dynamically but while removing, I thought to remove it from the opposite order and later to implement it differently; if I press the remove button I was getting an error in the console part as shown in this image:; can anyone find the problem in my code, if I test only that remove function separately then that works but not in bellow mentioned code
<body>
<div>Hello world</div>
<div id="li">
<input type="text" id="liin" name="in"/>
<button name="add" onclick=add() className="btn btn-light">add</button>
</div>
<script>
var i =1;
function add() {
let temp = document.getElementById('liin').value;
document.getElementById('li').innerHTML =`<br><span id="divli${i}">${temp}</span>
<button name="add" onclick=remove() className="btn btn-light">remove</button>`;
i ;
}
function remove() {
document.getElementById(`divli${i}`).innerHTML ='';
i--;strong text
}
</script>
</body>
CodePudding user response:
Try this. You are incrementing the i value too late in the code so your reference to select the element is coming in a null. Another thing you'll want to do is add a class to each 'remove' button to be selected and removed in the remove function as well. This can be done dynamically as well.
<body>
<div>Hello world</div>
<div id="li">
<input type="text" id="liin" name="in"/>
<button name="add" onclick=add() className="btn btn-light">add</button>
</div>
<script>
var i = 0;
function add() {
i ;
let temp = document.getElementById('liin').value;
document.getElementById('li').innerHTML =`<br><span id="divli${i}">${temp}</span>
<button name="add" onclick=remove() id="divli${i}" className="btn btn-light">remove</button>`;
}
function remove() {
// document.getElementById(`divli${i}`).innerHTML = '';
let nodeList = document.querySelectorAll(`#divli${i}`);
nodeList.forEach(node => node.remove());
i--;
}
</script>
</body>