Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript (pure) select first element (table)

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>
like image 708
AMD Avatar asked Jan 14 '13 10:01

AMD


3 Answers

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.

like image 150
97ldave Avatar answered Nov 08 '22 08:11

97ldave


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
like image 30
Christofer Eliasson Avatar answered Nov 08 '22 07:11

Christofer Eliasson


You can use getElementsByTagName() to get the tables collection and use 0 index for first table.

firstTable = document.getElementsByTagName('table')[0];
like image 4
Adil Avatar answered Nov 08 '22 08:11

Adil