Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - get all table -> tr > id values

Tags:

javascript

dom

I would like to access all the values of a table tr id field.

<table>
<tr id="1"></tr>
<tr id="2"></tr>
<tr id="3"></tr>
<tr id="4"></tr>
<tr id="5"></tr>
</table>

What I would like to do is, using a javascript function, get an array and have acess to

[1,2,3,4,5]

Thank you very much!

like image 512
Miguel Avatar asked Feb 15 '10 20:02

Miguel


People also ask

How can I get TD value?

How can I get input text value from inside TD? var data1 = $(this). find(“td:eq(0) input[type='text']”). val();

How do you calculate TR in a table?

To count the number of rows, the “#Table_Id tr” selector is used. It selects all the <tr> elements in the table. This includes the row that contains the heading of the table. The length property is used on the selected elements to get the number of rows.

How do you find the last tr in a table?

Approach 2: Use $('table tr:last') jQuery Selector to find the last element of the table. The 'table' in query looks for the table element then 'tr' is looking for all the rows in the table element and ':last' is looking for the last table row of the table.

What is TR ID in HTML?

The id attribute assigns an identifier to the <tr> element. The id allows JavaScript to easily access the <tr> element. It is also used to point to a specific id selector in a style sheet. Tip: id is a global attribute that can be applied to any HTML element.


2 Answers

var idArr = [];

var trs = document.getElementsByTagName("tr");

for(var i=0;i<trs.length;i++)
{
   idArr.push(trs[i].id);
}
like image 184
zincorp Avatar answered Sep 19 '22 21:09

zincorp


Please keep in mind that HTML ids must start with an alphanumeric character in order to validate, and getElementsByTagName returns a collection, not an array. If what you really want is an array of all your table rows, there's no need to assign an ID to each. Try something like this:

<table id="myTable">
<tr><td>foo</td></tr>
<tr><td>bar</td></tr>
<tr><td>baz</td></tr>
</table>

var i, tr, temp;

tr = [];
temp = document.getElementById('myTable').getElementsByTagName('TR');
for (i in temp) {
   if (temp[i].hasOwnProperty) {
      tr.push(temp[i]);
   }
}
like image 35
Kent Brewster Avatar answered Sep 18 '22 21:09

Kent Brewster