Quiero hacer un botón que cree un elemento ap, con un número de identificación creciente, cada vez que se presiona. El elemento p debe tener un botón de eliminación que eliminará solo el elemento principal.
Mi problema es que, aunque puedo crear el elemento y el botón Eliminar, la identificación está configurada como objeto indefinido. Debido a ese problema, elimina el primer elemento que creé. Por ejemplo, si creo 5 elementos, eliminaré el elemento 0, luego el elemento 1, etc.
let j = 0; let btnSubmit = document.getElementById('createElement'); btnSubmit.addEventListener('click', createIdElement); let divIdElement = document.getElementById("test"); function createIdElement() { let div1 = document.createElement('div'); let paragraph = document.createElement('p'); div1.setAttribute("id", toString(j)); paragraph.innerText = "This is a new Element with id " + j; let btnDelete = document.createElement('button'); btnDelete.setAttribute("id", toString(j)); btnDelete.textContent = 'Delete'; btnDelete.addEventListener('click', deleteIdElement); div1.append(paragraph, btnDelete) divIdElement.append(div1); j++; } function deleteIdElement() { let element = document.getElementById(toString(j)); element.remove(); j--; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <button type="submit" id="createElement">Create</button> <br> <div id="test"></div> <script src="mytest.js"></script> </body> </html>Como siempre, gracias de antemano por su tiempo y ayuda y disculpe si esto se ha preguntado antes.
Los detalles se comentan en el ejemplo, así como lo que estaba mal con el OP. Se agregó un <form> y se cambiaron algunas cosas para mayor claridad. Aquí hay algunos enlaces de lo que se mencionó en los comentarios:
let j = 0; /* HTMLFormElement interface is easier to use than other DOM interfaces. */ // This is <form id='UI'> const UI = document.forms.UI; /* Add .elements property to form object and you can reference any form control with id or name */ const IO = UI.elements; // This the <fieldset id='test'> const test = IO.test; // This is <button id='create'> IO.create.addEventListener('click', createGroup); function createGroup(event) { const div = document.createElement('div'); const par = document.createElement('p'); const btn = document.createElement('button'); /* In the OP (Original Post) the <div> was only being assigned a number as id which is invalid ids, classes, etc must start with a letter. */ div.id = 'id' + j; par.textContent = `This is a new Element with ${div.id}`; /* There's no need for id's on everything So the <button> is assigned a class which it actually isn't needed as you'll see further down */ btn.className = 'del'; btn.textContent = 'Delete'; btn.addEventListener('click', deleteGroup); div.append(par, btn) test.append(div); j++; } /* By default all event handlers (functions such as these two) pass the Event Object by default. The event obj has many useful properties, one in particular is Event.target. .target property always points to the element the user actually clicked or interacted with. */ /* So it will find the <button> the user clicked and find it's parent (div#id*) and remove it (and in doing so remove itself and it's sibling <p>) */ function deleteGroup(event) { event.target.parentElement.remove(); } /* Also, you shouldn't decrement j-- if you do then you'll end up with duplicated ids which is very invalid and problematic. */ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form id='UI'> <button id="create" type="button">Create</button> <br> <fieldset id="test"></fieldset> </form> </body> </html>Primero debe eliminar toString(j) , simplemente escriba j Y si desea eliminar la identificación específica con el botón específico, debe pasar el evento.
Aquí hay un ejemplo de trabajo:
https://jsfiddle.net/7n1etxsr/1/