1

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?

0

1 Answer 1

1

tested and working

$(document).ready(function() {

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

})

other solution

 $(document).ready(function() { var i=1;
    $(".test").each(function() { 
   if(i!=1) {
    var row = '<td style="background: red">b_'+ i +'</td>';    
                    $(this).before(row);
    }
                    i=i+1;
})  });
10
  • have you tried above code. it's adding duplicates yar please run your system above code you will know what happening. above code also adding duplicate. Please provide possible solution.
    – Magento007
    Jun 24, 2016 at 10:21
  • every tr add one td only not both. here adding 2 td's for all tr i.e row.
    – Magento007
    Jun 24, 2016 at 10:23
  • added another solution kindly try and feedback Jun 24, 2016 at 10:26
  • 1
    @Magento007 added the second solution and it is working tested by mysqlef. Jun 24, 2016 at 10:33
  • but not for first row. for adding first row is not require
    – Magento007
    Jun 24, 2016 at 10:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.