kaidentity
kaidentity

Reputation: 608

jquery addClass only applied to every second table row

I'm having a table with an jquery onClick event on the tr-rows. I want to highlight the currently selected row. "To highlight" means: change background color and normal font to italic font. So I created a class "selected_row" and in the onClick I'm adding the class to the row. Before, I'm removing the class from all other rows in order to delete highlighting from previously highlighted rows. The thing is that it works fine but only for every second row. This is running in IE8. I was checking with developer tools in IE8 and while the selected_row class is really applied and visible there for every row with index 1, 3, 5, ... it is not applied or visible in the DOM tree in the debugger for rows with index 0, 2, 4, ... I'm clueless. There is no difference whatsoever between the rows with odd and even index.

Here's part of the code:

table th {
    background-color: #ededed; 
    padding: 5px;
}
table td {
    padding: 5px;
}
.selected_row {
    font-style: italic;
    background-color: #eeeeee;
}

JavaScript:

var tableRowClickHandler = function () {
    if ($(this).hasClass ("header")) {
        // alert ('has class');
    }
    else {
        var _this = $(this)
        if (_this.hasClass ("selected_row")) {
            _this.removeClass ("selected_row");
        }
        else { 
            $("tr").each (function () {
            if (!$(this).hasClass ("header"))
                $(this).removeClass ("selected_row");
            });
            _this.addClass ("selected_row");
        }
    }
};

Upvotes: 0

Views: 400

Answers (2)

kaidentity
kaidentity

Reputation: 608

I solved the problem by not adding the styles through a class but by 2 individual css () calls setting the color and the font-style. This works fine and that is sufficient for me. Don't know why it doesn't work with addClass ().

Upvotes: 0

Pulkit Mittal
Pulkit Mittal

Reputation: 6086

I think you can make this function smaller:

var tableRowClickHandler = function () {
    if ($(this).hasClass ("header")) {
        return;
    }
    else {
        $("tr").removeClass ("selected_row");
        $(this).addClass ("selected_row");
    }
};

Upvotes: 1

Related Questions