CSS/jQuery selector for a table column

Asked

Viewed 1,564 times

7

Is there a CSS or jQuery selector that takes a column from a table (each td column)?

Or, if there isn’t a simple selector that can do it, you can do it with a little code in jQuery/Javascript?

  • can be more specific? why not use a class and catch this clasee through CSS or Jquery?

  • Because I wanted to learn a Generic way.

2 answers

9


If none of the Tds own a colspan then it is possible to do this using the pseudo-class :nth-child:

Example to select all third party Tds:

table td:nth-child(3) {
    /* estilo */
}

Reference in the MDN

Browser support:

jQuery has no problems with this, it works on the browsers supported by the library.

But in terms of CSS, it works from IE 9. You could use jQuery in IE 8 or smaller to assign the CSS you want using this pseudo-class, or you could use the following CSS that uses the pseudo-class :first-child and the local operator (called Adjacent sibling selectors):

table td:first-child + td + td {
    /* estilo */
}
  • 2

    +1 I was trying to do with :eq, but it didn’t work, but your method works. jsfiddle (Note: it is good to note that this index is based on 1, not in 0)

  • @mgibsonbr: you mean the content of the :eq is zero based, is not?

  • Yes the :eq is. But by the fiddle above, the :nth-child is one based.

  • The other answer worried me, because I need to use in old browsers. If you know any alternative can add the answer?

  • @Joaopaulo If you do via jQuery - instead of via CSS - it takes care of these details for you, doesn’t it? (simulating features that the browser does not natively support)

1

The answer from @Miguel Angelo will solve your problem.

However, since it is CSS3 http://www.w3schools.com/cssref/sel_nth-child.asp

You will not be able to use in old browsers.

You could use a class to define a specific column ex:

<table style="width:300px">
<tr>
  <td class="Coluna1">Jill</td>
  <td>Smith</td> 
  <td>50</td>
</tr>
<tr>
  <td class="Coluna1">Eve</td>
  <td>Jackson</td> 
  <td>94</td>
</tr>
</table>

After that you can take this column by CSS or by Jquery

CSS

.Coluna1{
//Codigo aqui
}

Jquery

$('.Coluna1)
  • It was worth the intention, but so I already know. It was just to know some more generic way that can be applied quickly on any page.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.