Hari Krishnan
Hari Krishnan

Reputation: 814

How to find which th child has the particular class for a table using jquery?

How to find which th child has the class 'nosort' for the table with 'normal-sort-table' class using jquery ? I want to alert column number of th with 'nosort' class.

<table class="normal-sort-table">
    <thead>
        <tr>
            <th>#</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th class="nosort">Username</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>Mark</td>
            <td>Otto</td>
            <td>mark246</td>
        </tr>
    </tbody>
</table>
<script>
$( document ).ready(function() {

    if ( $('.normal-sort-table tr th').hasClass( "nosort" ) ) {alert( 'column-number-with-nosort-class-alert-here' )}


})
</script>

Upvotes: 0

Views: 81

Answers (3)

Sadikhasan
Sadikhasan

Reputation: 18600

If you want to exact column number then you have write

alert($('th.nosort').index()+1);

becuase index starting from zero.

alert($('th.nosort').index());

alert($('th.nosort').index()+1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table class="normal-sort-table">
        <thead>
            <tr>
                <th>#</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th class="nosort">Username</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>Mark</td>
                <td>Otto</td>
                <td>mark246</td>
            </tr>
        </tbody>
    </table>

Upvotes: 0

yeswanth
yeswanth

Reputation: 1549

alert($("th").index($(".nosort")));

Upvotes: 1

A. Wolff
A. Wolff

Reputation: 74420

you can use jq .index() method:

$('.normal-sort-table tr th.nosort').index()

Upvotes: 1

Related Questions