Bojjaiah
Bojjaiah

Reputation: 261

Adding a td for existing table using jQuery

I am trying to add a td for existing table using jQuery. But it's adding duplicate. How to validate exactly to add the td.

I have tried below code:

<table>
<thead>
<tr>
    <th>head1</th>
    <th>head2</th>
    <th>head3</th>
    <th>head4</th>
</tr>
</thead>
    <tbody>
        <tr >
            <td class="test test2">a1</td>
            <td>a2</td>
            <td>a3</td>
        </tr>
        <tr>
            <td class="test">c1</td>
            <td>c2</td>
            <td>c3</td>
        </tr>            
    </tbody>
</table>

jQuery code

    <script>
       $(document).ready(function() {

       for(i=0;i<2;i++){
         var row = '<td style="background: red">b_'+ i +'</td>';    
                $('[class="test"]').before(row);
       }

})
        </script>

I want to add a td where exactly match the class="test" is, but it's adding both class="test test2" and class="test".

How can I do this?

Upvotes: 2

Views: 336

Answers (1)

Thulasiram
Thulasiram

Reputation: 8552

$(document).ready(function() {
       var length=  $('[class="test"]').length;
       for(i=0; i<length; i++){
         var row = '<td style="background: red">b_'+ i +'</td>';    
         $('[class="test"]:eq('+(i)+')').before(row);
       }
});

Demo: https://jsfiddle.net/Lqkmu7L1/

Upvotes: 2

Related Questions