let targets = document.getElementsByTagName('th');
//------------Added to ensure we delete the th which are not already deleted.
// (delete here means setting display: none to that particular element)
let indices = []
for(var i = 0 ; i < targets.length; i++) {
indices.push(i);
}
//-------------------------------------
let butDelete = document.createElement('button');
butDelete.innerHTML = 'Delete th';
document.body.appendChild(butDelete);
butDelete.addEventListener('click', function(){
let randIndex = Math.floor(Math.random() * (indices.length));
/*
* we pick a random index from indices
* as we know for sure that at any time, indices stores
* only those indices of th(in the targets array)
* whose display:none is not already set
*/
let delIndex = indices.splice(randIndex, 1)[0];
targets[delIndex].style.display = 'none';
});
table th {
height: 10px;
width: 50px;
border: 1px solid black;
}
table {
height: 200px;
width: 360px;
}
<table class="border" id="myTable">
<tr>
<th colspan="2">1</th>
<th>2</th>
<th>3</th>
<th>4</th>
</tr>
<tr>
<th>5</th>
<th>6</th>
<th>7</th>
<th>8</th>
<th>9</th>
</tr>
<tr>
<th>10</th>
<th>11</th>
<th>12</th>
<th>13</th>
<th>14</th>
</tr>
<tr>
<th>15</th>
<th>16</th>
<th>17</th>
<th>18</th>
<th>19</th>
</tr>
</table>