Search code examples
javascriptcsshtml-table

Click table row and get value of all cells


I don't know JQuery, so I'm hoping there is a way to do this in pure Javascript.

I need to click on a table row and get the value of each cell in that row. Here is the format of my table:

<table class='list'>
    <tr>
        <th class='tech'>OCB</th>
        <th class='area'>Area</th>
        <th class='name'>Name</th>
        <th class='cell'>Cell #</th>
        <th class='nick'>Nickname</th>
    </tr>
    <tr onclick="somefunction()">
        <td>275</td>
        <td>Layton Installation</td>
        <td>Benjamin Lloyd</td>
        <td>(801) 123-456</td>
        <td>Ben</td>
    </tr>
</table>

Is there anyway short of putting a unique ID to each cell?


Solution

  • There is no need to add ids or add multiple event handlers to the table. One click event is all that is needed. Also you should use thead and tbody for your tables to separate the heading from the content.

    var table = document.getElementsByTagName("table")[0];
    var tbody = table.getElementsByTagName("tbody")[0];
    tbody.onclick = function (e) {
        e = e || window.event;
        var data = [];
        var target = e.srcElement || e.target;
        while (target && target.nodeName !== "TR") {
            target = target.parentNode;
        }
        if (target) {
            var cells = target.getElementsByTagName("td");
            for (var i = 0; i < cells.length; i++) {
                data.push(cells[i].innerHTML);
            }
        }
        alert(data);
    };
    <table class='list'>
        <thead>
            <tr>
                <th class='tech'>OCB</th>
                <th class='area'>Area</th>
                <th class='name'>Name</th>
                <th class='cell'>Cell #</th>
                <th class='nick'>Nickname</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>275</td>
                <td>Layton Installation</td>
                <td>Benjamin Lloyd</td>
                <td>(801) 123-456</td>
                <td>Ben</td>
            </tr>
        </tbody>
    </table>

    Example:

    http://jsfiddle.net/ZpCWD/