简体   繁体   中英

Get the value of table cell in a row (JS or jQuery)

I have a table that incorporates 50 identical

<tr>
    <td>#</td>
    <td>#</td>
    <td>123123</td>
</tr>
...

and now I am able to get the value of a specific row like this

$("#tableId tbody tr").each(function(){
    var a = $(this).children();
    var arr =a[2].innerText; //get each row
    a[2].innerText = statename // get the third cell in each row
});

In this case, statename is an object with 50 states names. All I want to do now is to substitute that 123123 to each state name inside the object. So that it looks like this:

<tr>
    <td>#</td>
    <td>#</td>
    <td>Alabama</td>
</tr>
<tr>
    <td>#</td>
    <td>#</td>
    <td>Alaska</td>
</tr>
<tr>
    <td>#</td>
    <td>#</td>
    <td>Arizona</td>
</tr>
...

I tried to loop within the jQuery but it did not work. Please help, thank you very much.

You can try to use each method with find method, in the selector name, you can search the last <td> element by td:last . Like this:

 var statenames = ['Alabama', 'Alaska', 'Arizona']; $("#tableId tbody tr").each(function(index){ $(this).find('td:last').text(statenames[index]); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="tableId"> <tbody> <tr> <td>#</td> <td>#</td> <td>123123</td> </tr> <tr> <td>#</td> <td>#</td> <td>123123</td> </tr> <tr> <td>#</td> <td>#</td> <td>123123</td> </tr> </tbody> </table>

By using vanilla js, you can easily get the last td elements in tr, loop through them and assign new values to the nodes

 const stateNames = ['Alabama', 'Alaska', 'Arizona']; document.querySelectorAll('tr td:last-child') .forEach((x, i) => x.textContent = stateNames[i])
 <table> <tr> <td>#</td> <td>#</td> <td>123123</td> </tr> <tr> <td>#</td> <td>#</td> <td>123123</td> </tr> <tr> <td>#</td> <td>#</td> <td>123123</td> </tr> </table>

Make sure your variable statename is an array, and don't forget the index of the state

// find elements
statename = ["Alabama", "Alaska", "Arizona"]
$("#tableId tbody tr").each(function(index){
    var a = $(this).children();
    var arr =a[2].innerText; //get each row
    a[2].innerText = statename[index] // get the third cell in each row
});

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