JSFiddle - React, Tailwind, and code Playground
HTML
<table id="demoTbl" contenteditable>
<thead>
<tr>
<th title="Click to select column">
Col 1
</th>
<th title="Click to select column">
Col 2
</th>
</tr>
</thead>
<tr>
<td>
Row 1, Cell 1
</td>
<td>
Row 1, Cell 2
</td>
</tr>
<tr>
<td>
Row 2, Cell 1
</td>
<td>
Row 2, Cell 2
</td>
</tr>
<tr>
<td>
Row 3, Cell 1
</td>
<td>
Row 3, Cell 2
</td>
</tr>
</table>
CSS
th
{
background-color: gray;
color: white;
cursor: pointer;
}
TD
{
border-style: solid;
border-width: 1px;
text-align: center;
}
JavaScript
function SelectColumn(index, tableId) {
var columnText = 'You selected:\n\n';
var columnSelector = '#' + tableId + ' tbody > tr > td:nth-child(' + (index + 1) + ')';
var cells = $(columnSelector);
// clear existing selections
if (window.getSelection) { // all browsers, except IE before version 9
window.getSelection().removeAllRanges();
}
if (document.createRange) {
cells.each(function(i, cell) {
var rangeObj = document.createRange();
rangeObj.selectNodeContents(cell);
window.getSelection().addRange(rangeObj);
columnText = columnText + '\n' + rangeObj.toString();
});
}
else { // Internet Explorer before version 9
cells.each(function(i, cell) {
var rangeObj = document.body.createTextRange();
rangeObj.moveToElementText(cell);
rangeObj.select();
columnText = columnText + '\n' + rangeObj.toString();
});
}
//alert(columnText);
}
$(document).ready(function() {
$('#demoTbl thead th').each(function(index) {
$(this).click(function() {
SelectColumn(index, 'demoTbl');
});
});
});