Я новичок в javascript, и в настоящее время мне нужна отдельная функция удаления. Я решил использовать variable.removeChild()
, но он удаляет 2 входа
document.addEventListener('DOMContentLoaded', () => {
document.getElementById("delete").addEventListener("click", function deletes(){
var parent = document.getElementById("list");
var child = parent.getElementsByTagName("li")[0];
console.log(child);
parent.removeChild(child); //deletes a pair of my li inputs
});
});
Вот как выглядит мой код HTML
<body>
<h1>LIST</h1>
<h2>Items: </h2>
<div>
<ol id="list">
<li>test</li>
</ol>
</div>
<form id="insert">
<input type="text" id="itemInput" placeholder="Item" name="item">
<input type="submit" id="add" value="Add">
</form>
<input type="submit" id="search" value="Search"> //search doesn't do anything yet
<input type="submit" id="delete" value="Delete first item"> //Here is where it begins
</body>
Вот моя другая функция. Я также использую addEventListener (), возможно, в этом проблема? Этот код позволяет мне динамически добавлять элементы списка по желанию пользователя
document.addEventListener('DOMContentLoaded', () => {
//calls function once #insert has submit a form/hit the input
document.querySelector('#insert').onsubmit = () => {
//create variable
if(document.querySelectorAll('li').length >= 10){
return false;
};
//get the value of the input
let name = document.querySelector('#itemInput').value;
//stores value in the h3 tag
//create element of 'li'
const li = document.createElement('li');
//add the contents to the value of 'name'
li.innerHTML = name;
//now append the element to the #list section
document.querySelector('#list').append(li);
//gets the length of all the list items (li) and stored it in counter
counter = document.querySelectorAll('li').length;
//change the h2 tag with the updated list items
document.querySelector('h2').innerHTML = `Items: ${counter}`;
//prevents the form from submitting (good for debugging!!!)
return false;
};
});