Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make entire column disappear

How can I make the left column in a table disappear using plain JS?

This is my approach:

<table id="tab" border="1">
    <tr>
        <td>abc</td>
        <td>def</td>
    </tr>
    <tr>
        <td>ghi</td>
        <td>jkl</td>
    </tr>
    <tr>
        <td>mno</td>
        <td>pqr</td>
    </tr>
</table>

<button onclick="inv()">invisible</button>
<button onclick="vis()">visible</button>

<script>
var tab, td;
window.onload = function() {
    tab = document.getElementById("tab");
    td = tab.getElementsByTagName("td");
}

function inv() {
    for (i = 0; i < td.length; i++) {
        td[i].style.display = "none";
        i++;
    }
}

function vis() {
    for (i = 0; i < td.length; i++) {
        td[i].style.display = "block";
        i++;
    }
}
</script>

It works, but I have to use "ugly" loops.
Maybe there is a more efficient way by just saying column[0].display = "none".

Here is the fiddle.

like image 812
Evgenij Reznik Avatar asked Nov 11 '15 10:11

Evgenij Reznik


1 Answers

Take advantage of CSS hierarchy and nth-child selectors.

Use selector tr td:nth-child(1) to select all the first column td elements.

JSfiddle

var tab;
// Use DOMContentLoaded instead of load event
document.addEventListener('DOMContentLoaded', function() {
  tab = document.getElementById('tab');
});

function inv() {
  tab.classList.add('hide');
}

function vis() {
  tab.classList.remove('hide');
}
.hide tr td:nth-child(1) {
  display: none;
}
<table id="tab" border="1">
  <tr>
    <td>abc</td>
    <td>def</td>
  </tr>
  <tr>
    <td>ghi</td>
    <td>jkl</td>
  </tr>
  <tr>
    <td>mno</td>
    <td>pqr</td>
  </tr>
</table>
<button onclick="inv()">invisible</button>
<button onclick="vis()">visible</button>

Demo using toggle with single button.

function toggle() {
  document.getElementById('tab').classList.toggle('hide');
}
.hide tr td:nth-child(1) {
  display: none;
}
<table id="tab" border="1">
  <tr>
    <td>abc</td>
    <td>def</td>
  </tr>
  <tr>
    <td>ghi</td>
    <td>jkl</td>
  </tr>
  <tr>
    <td>mno</td>
    <td>pqr</td>
  </tr>
</table>
<button onclick="toggle()">Toggle</button>
like image 170
Tushar Avatar answered Oct 10 '22 07:10

Tushar