1

I have a table the code is ,

<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</table>

from the above code i want to add class="row1" in to the each tr by increment id example

<table>
    <tr class="row1">
    <td class="row11">1</td>
    <td class="row12">2</td>
    <td class="row13">3</td>
    </tr>
    <tr class="row2">
    <td class="row21">1</td>
    <td class="row22">2</td>
    <td class="row23">3</td>
    </tr>
    </table>

how to add the dynamic class id's in to tr and the td in the table , using jquery

1
  • I suggest you use the same class for each column, no need to increment class numbers. Will be simpler for CSS and using traverse methods easy to locate elements within a row Commented Dec 23, 2014 at 7:44

3 Answers 3

2
var counter=0;
$("#myTable tr").each(function(){
counter++;
    var self=$(this);
    self.addClass("row_"+counter);
    var tdCounter=0;
    self.find('td').each(function(){
    tdCounter++;
       $(this).addClass("row_"+counter+tdCounter);
    });
});

DEMO 1

Edited: Code to set margin-left of 1st td for each row

var counter = 0;
$("#myTable tr").each(function () {
    counter++;
    var self = $(this);
    self.addClass("row_" + counter);
    var tdCounter = 0;
    self.find('td').each(function (index) {
        tdCounter++;
        if (index == 0) {
            $(this).css({ "margin-left": 30,'float': 'left'});
        }
        $(this).addClass("row_" + counter + tdCounter);
    });
});

DEMO 2

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

1 Comment

anyway to add margin-left to the each tr first td with counter*30
1

Use:

$('tr').each(function(trindex){
  $(this).addClass('row'+(trindex+1));
  $(this).find('td').each(function(tdindex){
     $(this).addClass('row'+(trindex+1)+(tdindex+1));
});});

Working Demo

Comments

0
var i = 1;
$('table > tr').each(function() {
    $(this).addClass('row' + i);
    i++;
});

var n = 1
$('table > tr > td').each(function() {
    var that = $(this);
    var rowNum = that.closest('tr').attr('class').replace('row', '');
    $(this).addClass('row' + rowNum + n);
    n++;
});

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.