eozzy
eozzy

Reputation: 68730

Working with same class elements in a table

I want to set the width of th the same as tbody td if their classes match. I tried this but it doesn't seem to work:

$("#table th").each(function(i){
    var ClassName = $(this).attr('class');
    $(this).width( $("#table tbody td" + ClassName).outerWidth(true));
});

Upvotes: 0

Views: 50

Answers (2)

Konstantin Dinev
Konstantin Dinev

Reputation: 34905

Change your code to:

$("#table th").each(function(i){
    var ClassName = $(this).attr('class');
    $(this).width( $("#table tbody td[class*=" + ClassName + "]").outerWidth(true));
});

You need '.' for class selector.

Also note that attr('class') returns all the applied classes, which may be more than one, so you need to prefix each with '.'

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 359986

That's not how you generate a class selector. This is:

$("#table th").each(function(i){
    var ClassName = $(this).attr('class');

    // replace spaces with '.'s
    var classSelector = '.' + ClassName.replace(' ', '.');
    $(this).width( $("#table tbody td" + classSelector).outerWidth(true));
});

Upvotes: 4

Related Questions