Amicoderozer Amicoderozer - 4 months ago 30
Javascript Question

Jquery add css class to the first row of a table

Hi guys i'am trying to add a css class to the first tr of a table using jquery. I know this should be super easy, i found a lot of links and questions that provide correct solutions. Like these three and others:

How to get the id of first <tr> of <tbody> in HTML table using jQuery?

JQuery, select first row of table

how do i style the first row of every table on the page using jquery

But for me none of these works.

I have a table with id DataTableMovimenti and i want to apply the css class "ct-active"

I tried the following instructions:

$("#DataTableMovimenti tr:first").addClass('ct-active');
$("#DataTableMovimenti").find("tr:first-children").addClass("ct-active");
$("#DataTableMovimenti").find("tr:first").addClass("ct-active");
$("#DataTableMovimenti").find("tr:eq(0)").addClass("ct-active");
$("#DataTableMovimenti").find("tbody tr:eq(0)").addClass("ct-active");
$("#DataTableMovimenti").children("tr:first").addClass("ct-active");
$("#DataTableMovimenti").closest('tr').addClass('ct-active');


I inserted the code in the
$document.ready()
function in my jsp, because i want highlight the first row of the table when i enter the page.

The table have this structure:

<table id="DataTableMovimenti" class="table ct-datatables">
<thead>
<tr></tr>
............
</thead>
<tbody>
<tr id="tableRowId" class="table-row-tr"></tr>
...........
</tbody>
</table>


I want to change the css class of the first tr in the tbody section.
Thanks in advance

Answer

Add tbody in your selector.

$("#DataTableMovimenti tbody tr:first").addClass('ct-active');
.ct-active{
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="DataTableMovimenti">
  <thead>
    <tr>
      <td>First thead</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>First tbody</td>
    </tr>
     <tr>
       <td>Second tbody</td>
     </tr>
  </tbody>
</table>

It's better to do that with css.

#DataTableMovimenti tbody > tr:first-child {
  color:red;
 }
    <table id="DataTableMovimenti">
      <thead>
        <tr>
          <td>First thead</td>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>First tbody</td>
        </tr>
        <tr>
          <td>Second tbody</td>
        </tr>
      </tbody>
    </table>

Comments