简体   繁体   中英

How to get the first td value from tr with Javascript?

<tr>
  <td>Test Data</td>
  <td>2016</td>
  <td>59</td>
  <td>10-12-2014</td>
  <td><a href="#" class="delete-item secondary-content"><i class="fa fa-trash"></i></a></td>
 </tr>

I have a table where I have data in a row as it is defined above. What I want to do is, when the <i> is clicked then I want to get the first value of line which is "Test Data".

The rows are in a div which has id #list .

del(target,title) {
  if (target.className === 'fa fa-trash') {
    // Here I need the first td(which is the title) that I can compare in LocalStorage and delete that specific item
  }
}

document.getElementById('list').addEventListener('click', function (e) {
  const tr = e.target.parentElement.parentElement.parentElement;
  console.log(tr);

  del(e.target, title);
});

This gives the following console output:

 <tr> <td>Test Data</td> <td>2016</td> <td>59</td> <td>10-12-2014</td> <td><a href="#" class="delete-item secondary-content"><i class="fa fa-trash"></i></a></td> </tr> 

From this point, how can I reach the first <td> without using jQuery?

I would start by having your listener for the click a bit more specific so its not triggering on any click on the entire table.

Then you were very close by getting the tr , from there you can pass the tr into the del function and use getElementsByTagName on the tr to return the first td from the tr .

Then you can use removeChild to delete the first td you just queried from the tr parent node.

Here is an example:

 function del(e){ let firstTD = e.getElementsByTagName("td")[0]; console.log(firstTD); e.removeChild(firstTD); } document.querySelectorAll('#list .fa').forEach(function(trash) { trash.addEventListener('click', function(e) { const tr = e.target.parentElement.parentElement.parentElement; del(tr); }); }); 
 <div id="list"> <table> <tbody> <tr> <td>Test Data</td> <td>2016</td> <td>59</td> <td>10-12-2014</td> <td><a href="#" class="delete-item secondary-content"><i class="fa fa-trash">trash</i></a></td> </tr> <tr> <td>Test Data 2</td> <td>2015</td> <td>33</td> <td>11-23-2012</td> <td><a href="#" class="delete-item secondary-content"><i class="fa fa-trash">trash</i></a></td> </tr> </tbody> </table> </div> 

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