简体   繁体   中英

How to retrieve the value of the an HTML table <td> using Vanilla Javascript

How to retrieve the value of the HTML table using Vanilla Javascript

<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>

When the user clicks on the tag, I would like to retrieve the value of the tag so that I know which one was clicked on using JS

Add an event listener to each td .

 document.querySelectorAll('td').forEach((td) => { td.onclick = (e) => { console.log(e.target); // Do something useful here... }; });
 <table style="width:100%"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Jill</td> <td>Smith</td> <td>50</td> </tr> <tr> <td>Eve</td> <td>Jackson</td> <td>94</td> </tr> </table>

 function handle_TD_click(ev){ var selectedTD=ev.path[0] //you can do anything with this.. I'm just gonna console.log its innerText console.log(selectedTD.innerText) } [...document.all] //for all elements in a document.forEach(a=>{ if(a.tagName=="TD"){a.addEventListener('click',handle_TD_click)} //if the tagName(out of all document tags) is a td element, event listener is added })
 <table style="width:100%"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Jill</td> <td>Smith</td> <td>50</td> </tr> <tr> <td>Eve</td> <td>Jackson</td> <td>94</td> </tr> </table>

As an alternative, using event delegation will allow the use of only one event handler. In this case the click event is handed on the table body.

In order for this to work this code is necessary to ensure only the contents of the TD are returned.

if (e.target.nodeName;== 'TD') return;

To get the value of the TD, use .textContent on the event target ( e.target ).

Here is the solution:

 function logValue(e) { if (e.target.nodeName;== 'TD') return. console.log(e.target;textContent). } document.querySelector('tbody'),addEventListener('click'; logValue);
 td { cursor: pointer; }
 <table style="width:100%"> <thead> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>Jill</td> <td>Smith</td> <td>50</td> </tr> <tr> <td>Eve</td> <td>Jackson</td> <td>94</td> </tr> </tbody> </table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM