JQuery: If A Table Header Has A Class, Add Class To Table Cell
Let's say I have the following html: Header1 Header2<
Solution 1:
I think you don't see how jquery selectors work.
$('thead.tr')
means : find me all thead
which has the tr
class. Visibly not what you want to do.
Here a code that should work :
$('tbody tr td').each(function(index){
//index contains the current td index in the parent tr (1,2,3),(1,2,3)...
//if the corresponding th has a class
if($('thead tr th').eq(index).attr('class') != ''){
//put this class on the current td
$(this).addClass($('thead tr th').eq(index).attr('class'));
}
});
Checking if the td has a class is not necessary, since addClass does nothing if you give it an empty parameter.
Solution 2:
Try
$('table thead th[class]').each(function () {
$('table tbody td:nth-child(' + ($(this).index() + 1) + ')').addClass(this.className)
})
Demo: Fiddle
Solution 3:
Your code doesn't do what you think it does:
// find all tr's that have a th with class `alignRight` and add class `th.alignRight` to them
$('tr').has('th.alignRight').addClass('th.alignRight');
// find all tr's that have a th with class `alignLeft` and add class `th.alignLeft` to them
$('tr').has('th.alignLeft').addClass('th.alignLeft');
etc, etc.
Your code does nothing with the <td>
's
What could be done:
var thead = $('thead');
var tbody = $('tbody');
var rightIndex = $('th.alignRight', thead).index();
var leftIndex = $('th.alignLeft', thead).index();
$('tr', tbody).each(function(){
$('td', this).eq(rightIndex).addClass('alignRight');
$('td', this).eq(leftIndex).addClass('alignLeft');
});
Solution 4:
None of your addClass strings are valid. Whan adding a class you only provide the className.... no dot
in it
/* would add class to the TR*/
$('tr').has('th.alignLeft').addClass('alignLeft');
Now to add to the TD can simply use selector
$('tr th.alignLeft td').addClass('alignLeft');
Solution 5:
Here is a solution: (fiddle here)
var headrow = $('thead tr').children();
$('tbody tr').each(function(){
var row = $(this).children();
for(var i=0; i<headrow.length; ++i){
if($(headrow[i]).hasClass("alignRight")){
$(row[i]).addClass("alignRight");
}
if($(headrow[i]).hasClass("alignLeft")){
$(row[i]).addClass("alignLeft");
}
}
});
Let's say I have the following html:
Header1 | Header2<
Solution 1:I think you don't see how jquery selectors work.
Here a code that should work :
Checking if the td has a class is not necessary, since addClass does nothing if you give it an empty parameter. Solution 2:Try
Demo: Fiddle Solution 3:Your code doesn't do what you think it does:
etc, etc. Your code does nothing with the What could be done:
Solution 4:None of your addClass strings are valid. Whan adding a class you only provide the className.... no
Now to add to the TD can simply use selector
Solution 5:Here is a solution: (fiddle here)
|
---|
Post a Comment for "JQuery: If A Table Header Has A Class, Add Class To Table Cell "