i have two rows with same id in two different tables , i need both of these rows.i can get first using getElementById , but not able to get second. i have both table id's and row ids , is there any way to get that row directly by by using its table reference ?
3 Answers
Give them class say tablerows, as you can not have two elements with same id
Now get them one by one
var cusid_ele = document.getElementsByClassName('tablerows');
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
// Do whatever you want to do with this itm
}
4 Comments
davidethell
Looping over all the table rows in much less efficient, but if you have no control over the markup this would provide a way to find the second row that has the same id.
void
But their are just two
rows, Looping them is not inefficient.davidethell
The OP never said there were just two rows, only that there were two rows he needed to find. I still upvoted your answer, I just wanted to point out the efficiency problem if there were a lot of rows. Yours is the only way I know to solve this question if he can't or won't change the markup.
void
Yes you are right if the number of rows are large. Thanks for pointing it out.
You should have document wide unique ID (HTML4 specification) in ideal case.
In your case it will be more beneficial to use CSS Selector(nth-child) with the help of JS or JQuery. You may not even choose to use class, you can just work with <tr>. Follow the link here(MDN Selector) for CSS Selector reference.
3 Comments
Ravo
DOM has two div left and right each div has two tables and each table has rows with same id though both are different rows ,in UI it looks similar row .. i need highlight newly added row .well i am getting first row using getElementBy Id and second using table.rows looping till i get my desired row
Sidmeister
when you call getElementById, it searches for one unique ID. And because of the lax nature of html, it usually returns you the first one it finds in case there are multiple similar id's in the same document. So, no matter how many times you call the function, it will most likely return the element associated with the first instance of the id you are looking for.
Sidmeister
On the other hand, using css selector, you can preset the graphical formatting beforehand. You don't even need to bother when new rows are populated. If in css you apply special formatting to the last row or say, the n'th row, it will apply the formatting to the appropriate one always.
idmore than once. ID's are used to target a specific element (One of) If you want to target more than one element then you should use aclass. If you edit your question and display some source code you will find people can give you an example of how to fix your problem. No source code = nothing to work with.