jqueryhtml-tablecss-selectorsjquery-countdown

Count a th cell's place in table row


<table border="1">
    <tbody>
        <tr>
            <th>A</th>
            <th>B</th>
            <th>C</th>
        </tr>
        <tr>
            <td>aaa</td>
            <td>bbb</td>
            <td>ccc</td>
        </tr>
    </tbody>
</table>

How can I find out that the th cell with "B" is the second in the th row?

Test: http://jsfiddle.net/SNj27/1/


Solution

  • You could use eq() if it's always the second th element you want to target:

    $('th:eq(1)').text(); // returns 'B'
    

    Edit:

    If it's not always the second element, you could use index() to determine whether it is in the second row or not.

    if ($(this).text().trim() === "B") {
        console.log($(this).index()); 
        // Returns 1 and 2 respectively for your jsFiddle (0 index based) 
        // Meaning the first 'B' is in row 2, the second is in row 3.
    }
    

    jsFiddle.


    Note: You should use $.trim instead of trim(), as in IE8 and before, you will recieve a syntax error using trim():

    if ($.trim($(this).text()) === "B")
    

    jsFiddle.