Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to add class to first TD on each table row

I have a table I'm working with that is like such:

<table width="100%" border="0" cellspacing="0" cellpadding="0" id="tablecontent">
  <tr class="tablerow">
    <td>This is the td I want to add a class to.</td>
    <td class="cell2">Stuff</td>
    <td class="cell3">Stuff</td>
  </tr>
  <tr class="tablerow">
    <td>This is the td I want to add a class to.</td>
    <td class="cell2">Stuff</td>
    <td class="cell3">Stuff</td>
  </tr>
</table>

The first TD tag in each row does not have a class or ID to work with. I don't have access to change the HTML output so I figured to add in a bit of jQuery to target the first TD tag of each tablerow. How would I do this?

like image 232
Robert E Avatar asked Oct 13 '10 15:10

Robert E


People also ask

How to add class in table td using jQuery?

jQuery addClass() Method The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.

How can we append the first row in a table using jQuery?

append() / prepend() to Add Table Row in jQuery. To add a row in the table body using jQuery, we can use DOM inside insertion methods of append() or prepend() that adds an element to the suggested element's start or end. Here we will select the tbody element of table element with id="test" to add a row after it.

How can get TD table row value in jQuery?

jQuery: code to get TD text value on button click. text() method we get the TD value (table cell value). So our code to get table td text value looks like as written below. $(document). ready(function(){ // code to read selected table row cell data (values).


2 Answers

$('#tablecontent td:first-child').addClass('someClass');

This uses the first-child selector to select all <td> elements in the #tablecontent table that are a first-child of their parent.

Example: http://jsfiddle.net/duKKC/

like image 69
user113716 Avatar answered Oct 11 '22 05:10

user113716


You can try the below jQuery

$('.tablerow').each(function(index) {
    $(this).children('td').first().addClass('class');
});

This will solve your problem :)

like image 28
Scott Avatar answered Oct 11 '22 04:10

Scott