I have two tables like this:
<table>
<tr>
<td></td>
<td></td>
</tr>
</table>
<table>
<tr>
<td></td>
<td></td>
</tr>
</table>
They are all same. I have to select the first one (and the second) using pure javascript.
In jQuery it is $(table:first)
.
If tables were like this (with classes) could I use getElementByClassName('class')[0]
<table class="class">
<tr>
<td></td>
<td></td>
</tr>
</table>
<table class="class">
<tr>
<td></td>
<td></td>
</tr>
</table>
You can use:
var firstTable = document.getElementsByTagName("table")[0]
which is cross-browser compatible.
For newer browsers you could use:
var firstTable = document.querySelector("table")
which will select the first table.
You could use .getElementsByTagName("table")
on the document
, which will return a NodeList
containing all tables within the document. NodeLists are array-like objects and the tables are returned in the same order as they have in the document, so you could then just take the first element using its index.
var firstTable = document.getElementsByTagName("table")[0];
NodeLists are live
It is worth noting that the NodeList
returned by .getElementsByTagName()
is live, meaning that if you do DOM-manipulations after your call to .getElementsByTagName()
, those manipulations will be reflected in your list.
var tables = document.getElementsByTagName("table");
var firstTableBefore = tables[0];
/*
If you then prepend a new table to the body at this point, calling tables[0]
again will now return the newly added element
*/
var firstTableAfter = tables[0];
// firstTableBefore and firstTableAfter will NOT be the same
You can use getElementsByTagName() to get the tables collection and use 0 index for first table.
firstTable = document.getElementsByTagName('table')[0];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With