Ravi
Ravi

Reputation: 4095

Applying CSS to first & last TH of a table

I need to apply styles for the first and last th of the below table using jQuery, wrote some script which is not firing..

 <script>$("th:gt(0)").css("border-left", "none");</script>

 <table>
 <tr>
  <th scope="col">one</th>
  <th scope="col">two</th>
  <th scope="col">three</th>
</tr>
<tr>
  <td>1</td>
  <td>2</td>
  <td>3</td>
</tr>
</table>

Any help would be handy.

Upvotes: 0

Views: 2283

Answers (3)

Bojangles
Bojangles

Reputation: 101553

You can use :first-child and :last-child pseudo-selectors:

$("table tr th:first-child, table tr th:last-child").css("border-left", "none");

To only apply CSS to the last TH, you can use .last(), like this (keeping it one line):

$("table tr th:first-child, table tr th:last-child").css("border-left", "none").last().css("border-right", "none");

Upvotes: 5

rickyduck
rickyduck

Reputation: 4084

$('th:first, th:last').css("border-left", "none");

That should do the trick.

You can also use:

:last-of-type or :last-child

You can use these in your jQuery selector or just css, and use sizzlejs to provide cross browser.

Upvotes: 0

diagonalbatman
diagonalbatman

Reputation: 18012

I have never tried - but there are pseudo selectors called first-child and last-child. You may be able to target them this way.

However i am not sure on browser support?

Upvotes: 0

Related Questions