Skip to content Skip to sidebar Skip to footer

How Can I Apply Some Jquery Stuff Only Based On Header Row

I have the table like this:

Solution 1:

You can get the index of the header using .index() then apply the class using the :nth-child selector.

jsFiddle

enter image description here

var resultHeaderIndex = $('th:contains("result")').index();
$('td:nth-child(' + (resultHeaderIndex + 1) + ')').addClass('red')

If you wanted to add the class to the header also then you can simply add it before you get the index:

jsFiddle

enter image description here

var resultHeaderIndex = $('th:contains("result")')
    .addClass('red')
    .index();
$('td:nth-child(' + (resultHeaderIndex + 1) + ')').addClass('red')

Solution 2:

I think using jQuery .index() and .eq() you could do this pretty easily:

(function($){
    $.fn.colorColumn = function(headerText, color){
        var index = this.find("th").filter(function(){
            return ($(this).text() == headerText);
        }).css("backgroundColor", color).index();
        this.find("tr").each(function(){
            $(this).children().eq(index).css({backgroundColor: color});
        })
    }
})(jQuery);

$("table").colorColumn("number", "red");

working demo: http://jsfiddle.net/pitaj/eG5KE/

Solution 3:

The way I would do it is use a conditional and jQuery each:

$("th").each(function() {
    if ($(this).text() === "result") { $(this).addClass('red') }
}

Post a Comment for "How Can I Apply Some Jquery Stuff Only Based On Header Row"

id name number result