Add class to a datatable

Asked

Viewed 633 times

7

I’m making changes in a pagina.aspx of a system, however many things are generated through language functions.

Since I can’t add a class via code, I’m trying to add via jQuery, but I’m not getting it, below is an example of a code snippet.

<table id="ctl19_tableAreas" style="height:100%;width:100%">
    <tbody>
        <tr style="height:249px;">
            <td style="width:33%;padding-top:20px;" valign="top">
            </td>

            <td style="width:33%;padding-top:20px;" valign="top">
            </td>

            <td style="width:33%;padding-top:20px;" valign="top">
            </td>
        </tr>
    </tbody>
</table>

So my question is how do I add a class to these columns:

style=width:33%;
padding-top:20px;
valign=top

It can not be for all because within each has other tables, a total confusion.

  • $('#ctl19_tableAreas td').addClass('a_tua_classe'); should be enough to add the class. Can you explain better why you need the class and what you want to do? and also bring jQuery together to better understand the context.

  • I’ve already done this, the problem is that it will add the class in all td, and within td there are other tables. Need to add this class in order to be able to format 4 columns via css

  • 1

    If you use '#ctl19_tableAreas > tbody > tr > td' on the selector this will only select the td"1st generation" and not other tables within that first generation. That’s what you want?

  • I find very viable the answer of @Pedrocamarajunior

  • Exactly this I will, test a colleague’s solution posted below

  • Sergio, it worked perfectly as I wanted, thank you very much

Show 1 more comment

3 answers

1

You can use the Child selector jQuery

$("table#ctl19_tableAreas tr>td").addClass("myClass");
.myClass {
  width: 33%;
  padding-top: 20px;
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table id="ctl19_tableAreas" style="height:100%;width:100%">
  <tbody>
    <tr>
      <td>
        a
      </td>

      <td>
        b
      </td>

      <td>
        c
      </td>
    </tr>
  </tbody>
</table>

1

You can use the selector > indicating immediate progeny. For example #ctl19_tableAreas td will select all the td within this table with id ctl19_tableAreas but also tables within this table.

But using '#ctl19_tableAreas > tbody > tr > td' ensures that only td descendants of the first table are selected.

0

The most efficient way and using the datatable library itself. The number represents the table column, remembering that the count starts with 0.

columnDefs: [
    { className: "td-actions text-right", "targets": [ 4 ] },
],

Browser other questions tagged

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