Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data attribute of element when click on it or it child

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 />.

like image 639
kyun Avatar asked Dec 12 '18 12:12

kyun


2 Answers

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>
like image 109
Ramesh Rajendran Avatar answered Oct 04 '22 03:10

Ramesh Rajendran


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>
like image 22
Mohammad Avatar answered Oct 04 '22 04:10

Mohammad