Estoy tratando de agregar una casilla de verificación cuando se presiona el botón y también eliminar la misma casilla de verificación cuando se presiona eliminar. Desafortunadamente, la función de eliminación no se puede ejecutar porque parece que el div recién creado aún no existe. ¿Cómo puedo evitar esto?
<script> const list = document.getElementById("list"); const cli_form = document.getElementById("client-form"); let idz = 0; function add_client(input) { const div = document.createElement("div"); div.setAttribute("id", idz.toString()) const newCheckbox = document.createElement("input"); newCheckbox.setAttribute("type", 'checkbox'); newCheckbox.setAttribute("id", 'checkbox'); const newLabel = document.createElement("label"); newLabel.setAttribute("for", 'checkbox'); newLabel.innerHTML = input.value; const br = document.createElement("br"); const del = document.createElement("input"); del.setAttribute("type", 'button'); del.setAttribute("value", idz.toString()); del.onclick = delete_item(document.getElementById(idz.toString())); div.appendChild(newCheckbox); div.appendChild(newLabel); div.appendChild(del); div.appendChild(br); list.appendChild(div); idz++; } function delete_item(item1) { item1.remove(); } </script>Está asignando el resultado de la función delete_item que invoca inmediatamente. Por lo tanto, está eliminando el elemento antes de agregarlo a DOM. Puede usar un envoltorio de flecha para evitar la invocación inmediata. Como esto :
del.onclick = () => delete_item(document.getElementById(idz.toString()));