2

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?

2
  • use $('[class="test"]').before(row); instead of $('.test').before(row); Commented Jun 24, 2016 at 8:55
  • 1
    @ magento two: try with this selector $('[class="test"]:eq('+(i)+')').before(row); Commented Jun 24, 2016 at 12:54

1 Answer 1

2
$(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/

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.