0

I have a javascript which makes a table in HTML sortable. However I want to style the header of the column which is clicked using javascript.

How can I get the thead of the table? I know the column of the header which i need to change.

Here is what my javascript returns to me right now.

javascript

console.log(table.tHead);

output to console:

<thead>
        <tr>
            <th>Name</th>
            <th>Times Placed</th>
            <th>UMF (KB)</th>
            <th>UAC</th>
            <th>Texture Memory (MB)</th>
            <th>Texture Count</th>
            <th>Mesh Memory (KB)</th>
            <th>Mesh Count</th>
            <th>Path</th>
        </tr>
</thead>
JokerMartini
  • 5,674
  • 9
  • 83
  • 193

2 Answers2

3

This will add a selected class to a clicked th element, and it will remove the selected class from a previously-clicked th:

document.querySelector('thead').addEventListener('click', function(e) {
  var current;
  if (e.target.tagName === 'TH') {
    current = document.querySelector('th.selected');
    if (current) {
      current.classList.remove('selected');
    }
    e.target.classList.add('selected');
  }
});
th {
  border: 1px solid #bbb;
  padding: 0.5em;
}
.selected {
  background: #def;
}
<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Times Placed</th>
      <th>UMF (KB)</th>
      <th>UAC</th>
      <th>Texture Memory (MB)</th>
      <th>Texture Count</th>
      <th>Mesh Memory (KB)</th>
      <th>Mesh Count</th>
      <th>Path</th>
    </tr>
  </thead>
</table>

It should work with your existing code, assuming you have only one table on the page.

Rick Hitchcock
  • 35,202
  • 5
  • 48
  • 79
0

function makeMeBlue(element) {
  element.style.color = 'blue';
}
<table id="table">
  <thead>
    <tr>
      <th onclick="makeMeBlue(this)">Name</th>
      <th onclick="makeMeBlue(this)">Times Placed</th>
      <th onclick="makeMeBlue(this)">UMF (KB)</th>
      <th onclick="makeMeBlue(this)">UAC</th>
      <th onclick="makeMeBlue(this)">Texture Memory (MB)</th>
      <th onclick="makeMeBlue(this)">Texture Count</th>
      <th onclick="makeMeBlue(this)">Mesh Memory (KB)</th>
      <th onclick="makeMeBlue(this)">Mesh Count</th>
      <th onclick="makeMeBlue(this)">Path</th>
    </tr>
  </thead>
</table>
indubitablee
  • 8,136
  • 2
  • 25
  • 49