Hello,
I’m making table with list of some items, and in same row I have button to delete that item.
How I can achieve to get item name before deleting that item?
https://codepen.io/marklenon95/pen/ooqLWd
I’ve done it like this:
const button = document.querySelectorAll("td button");
button.forEach((el) => {
el.addEventListener('click', (e) => {
console.log(e.target.parentNode.parentNode.childNodes[1]);
});
});
Is there some other dynamic way so I can avoid hard coded array index?
If you have a class name on the td called “price” you could then use that instead.
<td class="price">29.00$</td>
var price = e.target.parentNode.parentNode.querySelector(".price");
console.log(price);
And if you use an upTo function, the code becomes even easier too.
function upTo(selector, el) {
while (!el.matches(selector)) {
el = el.parentNode;
}
return el;
}
...
var price = upTo("tr", e.target).querySelector(".price");
console.log(price);
1 Like
m3g4p0p
November 21, 2017, 8:30pm
3
You might use .firstElementChild
here… maybe it would also be a bit cleaner not to chain all those .parentNode
accessors but use .closest()
instead, like
console.log(e.target.closest('tr').firstElementChild.textContent)
Of course this would still make assumptions about the order of the elements; better yet would be using another .querySelector()
here. E.g. you could nicely incorporate some data-*
attributes like so:
<tr>
<td data-prop="name">Test1</td>
<td data-prop="price">29.00$</td>
<td><button>×</button></td>
</tr>
<tr>
<td data-prop="name">Test2</td>
<td data-prop="price">29.00$</td>
<td><button>×</button></td>
</tr>
<!-- etc. -->
const buttons = document.querySelectorAll("td button")
Array.from(buttons).forEach(button => {
button.addEventListener('click', event => {
const propEls = event.target
.closest('tr')
.querySelectorAll('[data-prop]')
const props = Array.from(propEls).reduce((data, el) => {
data[el.dataset.prop] = el.textContent
return data
}, {})
console.log(props) // something like { name: "Test1", price: "29.00$" }
})
})
(x-post)
1 Like
system
Closed
February 21, 2018, 3:30am
4
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.