Jonathan M
Jonathan M

Reputation: 17451

Is there a way to access an array of col tags for a table in javascript?

I have a table that looks like:

<table id="myTable">
    <col id="name" />
    <col id="birthYear" />
    <col id="phone" />
    <td>
        <tr>Joe</tr>
        <tr>1972</tr>
        <tr>202-555-1234</tr>
    </td>
</table>

Is there an easy way to get an array of the <col /> tags? I don't want to use getElementById because I don't know the ids of the col tags, although I will know the Id of the table. I don't want to use getElementsByTagName because there will be several tables in the document with col tags.

I'm not using jquery, just regular javascript.

Any ideas?

Upvotes: 7

Views: 278

Answers (2)

Marc B
Marc B

Reputation: 360762

Javascript supports XPath:

document.evaluate('//col', document.getElementById('myTable'));

Upvotes: 4

Jerome Cance
Jerome Cance

Reputation: 8183

getElementsByTagName can be used on table with id "myTable" : it will returns all col of this table.

here is an example :

document.getElementById("myTable").getElementsByTagName("col")

Upvotes: 5

Related Questions