I have this code in a loop ie: each delete button and csrf token shows as many times as there are database records:
<% for (const products of approved) { %>
<li>
<div class="list-box-listing">
<div class="list-box-listing-img"><a href="#"><img src="../<%= products.image %>" alt=""></a></div>
<div class="list-box-listing-content">
<div class="inner">
<h3><a href="#"><%= products.title %></a></h3>
<span><%= products.address.city %>, <%= products.address.suburb %></span>
<div class="star-rating">
<h5>Added <%= moment(products.createdAt).fromNow() %></h5>
</div>
</div>
</div>
</div>
<div class="buttons-to-right">
<a href="edit-listing/<%= products._id %>" class="button gray edit"><i class="sl sl-icon-note"></i> Edit</a>
<input type="hidden" name="_csrf" value="<%= csrfToken %>">
<a href="#" class="button gray delete" data-id="<%= products._id %>"><i class="sl sl-icon-close"></i> Delete</a>
</div>
</li>
<% } %>
I want to get the value of the csrf token that is in the same vicinity as the button that was clicked.
document.body.addEventListener("click", e => {
if (!e.target.matches(".delete")) return;
e.preventDefault();
const deleteBtn = e.target;
const csrf = document.querySelector("[name=_csrf").value;
const productId = deleteBtn.dataset.id;
console.log(csrf);
});
I tried using 'closest' but that was an epic fail.
const deleteBtn = e.target;
const csrf = deleteBtn.closest("[name=_csrf]").value;
I also tried:
const csrf = deleteBtn.parentNode.querySelector("[name=_csrf]").value;
But that gives me error:
Uncaught TypeError: Cannot read property 'value' of null at HTMLBodyElement.document.body.addEventListener.e