I am making a Table.
document.querySelector('table').addEventListener('click', (e) => {
console.log(e.target);
console.log(e.target.dataset.item);
})
td {
padding: 8px;
border: 1px solid black;
background-color: blue;
}
span {
background-color: red;
padding: 4px;
}
<table>
<tr>
<td data-item="item1"><span>1</span></td>
<td data-item="item2"><span>2</span></td>
<td data-item="item3"><span>3</span></td>
<td data-item="item4"><span>4</span></td>
<td data-item="item5"><span>5</span></td>
</tr>
</table>
When I click the BLUE PART, I can get data-item
attribute. But when I click the RED PART, I can't.
I wanna fix it, if I click <span/>
in <td/>
, I want to get data-item
attribute from <td />
.
Try to use closest
by your child tag instead of dataset
.
document.querySelector('table').addEventListener('click', (e) => {
console.log(e.target.closest("td").dataset.item);
})
td {
padding: 8px;
border: 1px solid black;
background-color: blue;
}
span {
background-color: red;
padding: 4px;
}
<table>
<tr>
<td data-item="item1"><span>1</span></td>
<td data-item="item2"><span>2</span></td>
<td data-item="item3"><span>3</span></td>
<td data-item="item4"><span>4</span></td>
<td data-item="item5"><span>5</span></td>
</tr>
</table>
Check if name of clicked element is span
select parent of it using parentNode
property
document.querySelector('table').addEventListener('click', (e) => {
var ele = e.target.nodeName == "SPAN" ? e.target.parentNode : e.target;
console.log(ele.dataset.item);
})
td {
padding: 8px;
border: 1px solid black;
background-color: blue;
}
span {
background-color: red;
padding: 4px;
}
<table>
<tr>
<td data-item="item1"><span>1</span></td>
<td data-item="item2"><span>2</span></td>
<td data-item="item3"><span>3</span></td>
<td data-item="item4"><span>4</span></td>
<td data-item="item5"><span>5</span></td>
</tr>
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With