sridhar
sridhar

Reputation: 1389

Adding id to html table row in JavaScript

The rows in my table have unique id, example: <tr id = "tb6"> I am appending new rows by javascript in this way:

var table = document.getElementById(f);
var row = table.insertRow();
var cell1 = row.insertCell();
var cell2 = row.insertCell();
cell1.innerHTML = text1;
cell2.innerHTML = text2;

How do I add id to this newly created row in vanilla javascript (not jquery).

Upvotes: 5

Views: 18421

Answers (2)

Katakam Nikhil
Katakam Nikhil

Reputation: 1385

First off, it is a really bad practice to have a unique ID for each table row. If you want to identify the table row, you can do that based on the data itself. Look at the concept of event bubbling. It is best to use the event.target and event.currentTarget to identify for which row you are firing the event. If you want to set an id for what you have, you can do this:

var table = document.getElementById(f); var row = table.insertRow(); var cell1 = row.insertCell(); var cell2 = row.insertCell(); row.id = "xyz"; //you can add your id like this cell1.innerHTML = text1; cell2.innerHTML = text2;

However, I must advise you it is a VERY BAD PRACTICE to use unique IDs for rows

Each row cannot be set a unique id every time. The idea is to utilize a naturally occurring phenomenon of event bubbling. So might as well use it. As the application scales itself, the ids have to become more and more versatile and that is a hassle in itself.

Upvotes: 3

epascarello
epascarello

Reputation: 207501

row.id = "foo";

or

row.setAttribute("id","foo");

Upvotes: 7

Related Questions