How can I apply some jquery materials based on title bar only

I have a table like this:

<table> <thead> <th>id </th><th>name </th><th>number </th><th>result </th> </thead> <tbody> <tr> <td>stuff</td> <td>stuff</td> <td>stuff</td> <td>stuff</td> </tr> </tbody> </table> 

I want to add class = "red" only to those td whose title is result

so only the result column with jquery is dynamic when the page loads.

+2
source share
3 answers

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

jsFiddle

enter image description here

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

If you want to add a class to the header, then you can just 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') 
+2
source

I think with 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/

+1
source

The way I did this is to use conditional and jQuery each :

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

Source: https://habr.com/ru/post/901562/


All Articles