Помогите настроить кнопку удаления динамических элементов. У меня есть код: https://www.w3schools.com/code/tryit.asp?filename=G2T2WSPSDUVS
Код :
<!DOCTYPE html>
<html>
<body>
<div>
<input type = "checkbox" id = "coffee" name = "coffee" checked>
<label for = "coffee">Coffee</label>
</div>
<div>
<input type = "checkbox" id = "gym" name = "gym">
<label for = "gym">Gym</label>
</div>
<div>
<input type = "checkbox" id = "rose" name = "rose">
<label for = "rose">Rose</label>
</div>
<button onclick = "myFunction()">Try it</button>
<ul id = "myList"></ul>
<script>
function myFunction() {
var node = document.createElement("LI");
var checkBoxCoffe = document.getElementById("coffee");
var checkBoxGym = document.getElementById("gym");
var checkBoxRose = document.getElementById("rose");
var textnode = document.createTextNode("");
if (checkBoxCoffe.checked == true){
textnode.textContent=textnode.textContent+"Coffee; "
}
if (checkBoxGym.checked == true){
textnode.textContent=textnode.textContent+"Gym; "
}
if (checkBoxRose.checked == true){
textnode.textContent=textnode.textContent+"Rose; "
}
var button = document.createElement("button");
button.innerHTML = "Remove";
node.appendChild(textnode);
node.appendChild(button);
document.getElementById("myList").appendChild(node);
}
</script>
</body>
</html>
Как я могу сделать, чтобы каждая кнопка удаляла точно выбранный элемент li? все работает только кнопку удалить еще нужно сделать Спасибо
Посмотрите на .addEventListener(). И поиск «dom remove element» (аналог "создатьЭлемент()") должен дать вам достаточно ресурсов для выполнения задачи.
в этом случае добавьте класс к кнопке, а затем привяжите событие нажатия к кнопке, а затем что-то вроде нажатия кнопки this.parentNode.remove();



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


добавить событие onclick к кнопке перед узел.appendChild (кнопка);
button.onclick = function(){
button.parentElement.remove()
return;
};
Вот что я пробовал. (Примечание: я предлагаю вам использовать что-то вроде `jquery', что облегчит многие вещи.
document.getElementById('add').addEventListener('click',function(){
addItems();
});
function addItems(){
var parent = document.createElement('div');
var text = document.createElement('input');
text.innerText = "Click button";
var button = document.createElement('button');
button.className = "btn";
button.innerText = "Click";
parent.appendChild(text);
parent.appendChild(button);
// this is something you are looking for.
button.addEventListener('click',function(){
this.parentNode.remove();
});
document.getElementById('test').appendChild(parent);
}<div id = "test">
</div>
<button id = "add"> Add more
</button>Удачного кодирования!
Зарегистрируйте событие клика в <ul>, а затем делегируйте событие клика фактической нажатой кнопке (event.target). Подробности прокомментированы в демо
// Register click event to button#add
document.getElementById('add').onclick = addItem;
// Reference <ul>
var list = document.getElementById('list');
function addItem(e) {
// Get all checked checkboxes
var chx = document.querySelectorAll('input:checked');
// Clear list
list.innerHTML = '';
// Loop through the checked checkboxes
for (let i = 0; i < chx.length; i++) {
// Create a <li>
var li = document.createElement('LI');
// Set <li> text to the checked checkbox label text
li.textContent = chx[i].nextElementSibling.textContent;
// Append a button to <li>
li.insertAdjacentHTML('beforeend', ` <button>×</button>`);
// Append <li> to <ul>
list.appendChild(li);
}
}
// Register click event to <ul>
list.onclick = removeItem;
function removeItem(e) {
// Reference the clicked tag
var tgt = e.target;
// if the clicked tag is a button...
if (tgt.tagName === "BUTTON") {
// Find the closest <li> to the clicked button and remove it
tgt.closest('li').remove();
}
// otherwise just terminate function
return false;
}<!DOCTYPE html>
<html>
<body>
<div>
<input type = "checkbox" id = "coffee" name = "coffee" checked>
<label for = "coffee">Coffee</label>
</div>
<div>
<input type = "checkbox" id = "gym" name = "gym">
<label for = "gym">Gym</label>
</div>
<div>
<input type = "checkbox" id = "rose" name = "rose">
<label for = "rose">Rose</label>
</div>
<button id='add'>ADD</button>
<ul id = "list"></ul>
</body>
</html>вы можете попробовать этот код
в этом коде я создаю простую функцию удаления для кнопки удаления.
button.onclick = removeli;
function removeli()
{
document.getElementById("myList").removeChild(node);
}
Возможный дубликат Как удалить родительский элемент с помощью простого javascript..!