Eddie
Eddie

Reputation: 621

How to create an id for a td element based on the row id?

I'm trying to generate the id of a td element, based on it's row number.

I believe that the td id must be unique. Maybe I am wrong? I'm therefore trying to concatenate the row number with some text but can't seem to get it to work.

We are using jQuery on our website and I can successfully create other id's which are based on variables, but i'm a little stuck on this one. Here's an example of something that works

<td id="person-id${person.id}">${person.name}</td>

The html will later look something like:

<td id="person1"></td><td id="person2"></td><td id="person3"></td> etc

I was hoping to do something like this for another table but having some trouble:

<td id="row-number("+rowIndex+")">some text here</td>

Any help would be appreciated.

Upvotes: 0

Views: 1392

Answers (1)

Chris Fowler
Chris Fowler

Reputation: 26

I'm assuming you want to assign the id based on column number, not row number. If I'm correct in this assumption, you can do it with jQuery like so:

$("tr").each(function() {
 $(this).children().each(function() {
 var n = $(this).index();
 $(this).attr('id','person'+n);
 });
});

Otherwise, if you do want the row number assigned to the id, it would be:

$("tr").each(function() {
 $(this).children().each(function() {
 var n = $(this).parent().index();
 $(this).attr('id','person'+n);
 });
});

Voila.

Upvotes: 1

Related Questions