Home > Software design >  Target one specific Jquery Data Table theader for CSS styles
Target one specific Jquery Data Table theader for CSS styles

Time:05-11

Working with a dynamic Jquery Data Table with 10 table headers. Not able to physically add in a class or an Id in code to the particular th whose title is 'Unused'.

In .css I have tried

[title~= Unused] {
    background-color: goldenrod !important;
    font-weight: 900 !important;
}

In jQuery I have tried:

$('th[data-title="Unused"]').css("color", "goldenrod");
$(row.Unused).css("color", "goldenrod");
$("row.Unused").css("color", "goldenrod")
$("row.Unused").addClass("highlight")

Any thoughts, suggestions?

CodePudding user response:

You can use the DataTables initComplete option.

This ensures the table has been initialized and the headings are available to be manipulated.

The following demo searches the headings for the title "Office" and then changes the font color for that heading:

$(document).ready(function() {

  $('#example').DataTable( {

    "initComplete": function ( settings ) {
      $('#example thead tr th').each(function() {
        if ($(this).html() === 'Office') {
            $(this).css("color", "goldenrod");
        }
      }); 
    }

  } );

} );
<!doctype html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Demo</title>
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
  <link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">


</style>

</head>

<body>

<div style="margin: 20px;">

    <table id="example"  style="width:100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Position</th>
                <th>Office</th>
                <th>Age</th>
                <th>Start date</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Tiger Nixon</td>
                <td>System Architect</td>
                <td>Edinburgh</td>
                <td>61</td>
                <td>2011/04/25</td>
                <td>$320,800</td>
            </tr>
            <tr>
                <td>Garrett Winters</td>
                <td>Accountant</td>
                <td>Tokyo</td>
                <td>63</td>
                <td>2011/07/25</td>
                <td>$170,750</td>
            </tr>
        </tbody>
    </table>

</div>

</body>
</html>

  • Related