Arvin
Arvin

Reputation: 1014

jquery filter function used to filter a class

A set of tr is there. and some tr pocess a class dblist_selected . I need to filter out the tr elements contain that class.I wrote a jquery code for that but its not working.

<table>
    <tbody id="tbodyDashBoard">
        <tr id="tr0" class="heading">
            <th>heading</th>
        </tr>
        <tr id="tr1" class="itemrow dblist_selected">
            <td>itemname1</td>
        </tr>
        <tr id="tr2" class="itemrow dblist_selected">
            <td>itemname2</td>
        </tr>
        <tr id="tr3" class="itemrow">
            <td>itemname3</td>
        </tr>
        <tr id="tr4" class="itemrow">
            <td>itemname4</td>
        </tr>
        <tr id="tr5" class="itemrow">
            <td>itemname5</td>
        </tr>
        <tr id="tr6" class="itemrow">
            <td>itemname6</td>
        </tr>
        <tr id="tr7" class="itemrow">
            <td>itemname7</td>
        </tr>
    </tbody>
</table>

This is the jquery code statement. I need the returned object in the variable selRow

var selRow = $("#divGridContainer").find("#tbodyDashBoard tr").filter(function () {
    return $(this).attr('class') == 'dblist_selected';
});

Is there any error in the code. How can I achieve my goal

Upvotes: 0

Views: 43

Answers (3)

Axel Amthor
Axel Amthor

Reputation: 11096

You may access these elements directly:

$("#divGridContainer").find("#tbodyDashBoard tr.dblist_selected").each( function (index, element) {
   // do stuff with element - jQuery(element)...
});

Upvotes: 1

Tushar
Tushar

Reputation: 87203

Problem:

The problem in the code is that the value of the attribute class is compared to the classname, so if the element contains other class, the condition will not be satisfied.

var selRow = $("#divGridContainer").find("#tbodyDashBoard tr").filter(function () {
    return $(this).attr('class') == 'dblist_selected';
});

For the elements the $(this).attr('class') will give string as 'itemrow dblist_selected' which is not equal to the string 'dblist_selected'. So, filtering will return no elements in the selRow variable.

Solution:

Use hasClass() to check if an element is having specified class.

var selRow = $("#divGridContainer").find("#tbodyDashBoard tr").filter(function () {
    return $(this).hasClass('dblist_selected');
});

There is no need to use filter, use descendant selector.

var selRow = $("#divGridContainer #tbodyDashBoard tr.dblist_selected");

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82231

You can rather use class selector along with classname to target element with class dblist_selected:

var selRow = $("#divGridContainer").find("#tbodyDashBoard tr.dblist_selected")

Upvotes: 1

Related Questions