5

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).

2

2 Answers 2

7
row.id = "foo";

or

row.setAttribute("id","foo");
Sign up to request clarification or add additional context in comments.

3 Comments

OP says: "I am appending new rows ..." Presumably the code is in a function, which is reused, and they want an unique id ...
@Teemu "How do I add id to this newly created row" I read it as the OP had no clue how to set an id. It is not that hard to add a counter...
Teemu, Epascarello, I had no clue how to set the id. Yes, I am using this in a function and the id will be assigned using a counter.
3

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.

8 Comments

Why is it VERY BAD PRACTICE?
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.
You should consider adding that to your answer now. I was merely trying to get you to explain why it is bad as you claimed it is bad.
@KatakamNikhil Perhaps you've meant static ids for rows are bad practice? Btw. the id you've set in your example is not unique.
@KatakamNikhil It was just a nitpick. Actually I pretty much agree with you about using ids for table rows.
|

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.