Necesito agregar un botón Eliminar en mis tarjetas, y este es el error que recibo.
Así es como se pidió que se hiciera. Lo encuentro por encima de mi conocimiento, pero en caso de que alguien tenga curiosidad, pensé que podría compartirlo.
const commentsUrl = "http://localhost:8080/comments"; let comments = []; function getComments() { fetch(commentsUrl, { method: "GET" }) .then((res) => res.json()) .then((data) => { comments = data; renderComments(comments); }); } const renderComments = (comments) => { const commentsContainer = document.getElementById("content"); commentsContainer.innerHTML = ""; comments.forEach(function (post) { const comment = document.createElement("div"); comment.innerHTML = ` <div id=${post.id} class="card"> <div class="card text-center bg-info" style="width: 18rem;"> <div class="card-body "> <h5 class="card-user ">${post.user}</h5> <h6 class="card-id mb-2 text-muted">Id: ${post.id}</h6> <p class="card-content">"${post.content}" </p> <p class="card-date">${post.date}<p> <button type="button" class="btn btn-primary btn-sm">Edit</button> <button type="button" class="btn btn-danger btn-sm" id="deleteBtn" onclick='remove(${post.id})'>Delete</button> </div> </div> </div>`; commentsContainer.append(comment); }); }; function remove(id) { fetch(`${commentsUrl}/${id}`, { method: "DELETE" }).then((comment) => { const index = comments.findIndex( (currentComment) => currentComment.id === comment.id ); comments.splice(index - 1, 1); renderComments(comments); }); } getComments();Intente mover la función deleteButton() fuera de la función getComments() .
function getComments() { fetch(commentsUrl, { method: "GET" }) .then((res) => res.json()) .then((data) => { data.forEach(function (post) { const randomId = Math.random().toString().substr(2, 8); const comment = document.createElement("div"); comment.innerHTML = ` <div class="card" id="${randomId}"> <div class="card text-center bg-info" style="width: 18rem;"> <div class="card-body "> <h5 class="card-user ">${post.user}</h5> <h6 class="card-id mb-2 text-muted">Id: ${post.id}</h6> <p class="card-content">"${post.content}" </p> <p class="card-date">${post.date}<p> <button type="button" class="btn btn-primary btn-sm">Edit</button> <button type="button" class="btn btn-danger btn-sm" id="deleteButton" onclick="deleteButton('${randomId}')">Delete</button> </div> </div> </div>`; document.getElementById("content").append(comment); }); }); } function deleteButton(id) { var del = document.getElementById(id); del.remove(); } window.onload = getComments(); Las funciones en Javascript crean un alcance para que las funciones definidas dentro de las funciones solo se puedan llamar dentro de esa función. Está creando un elemento HTML, que intentará llamar a deleteButton() desde el ámbito global y no tiene acceso a la declaración de función dentro de getComments() .
EDITAR: corrigió un poco más de código