Select cell content from html table
Javascript
HTML
<h1>Selektuj celiju i iskopiraj sadrzaj</h1>
<table id="tbl1" border="1">
<tr>
<td class="test">Sadrzaj prve celije</td>
<td>Druga celija</td>
</tr>
<tr>
<td>Milijan Radovic</td>
<td>Vladimir Vujovic</td>
</tr>
</table>
JavaScript
function selectCellText(e) {
e = e || window.event;
var obj = e.target || e.srcElement;
//document.getElementById('table').getElementsByTagName('td');
if (obj.nodeName.toLowerCase() === 'td') {
if (document.selection) { // IE
var range = document.body.createTextRange();
range.moveToElementText(obj);
range.select();
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(obj.firstChild);
window.getSelection().addRange(range);
}
}
}
function copySelectionText() {
var copysuccess // var to check whether execCommand successfully executed
try {
copysuccess = document.execCommand("copy") // run command to copy selected text to clipboard
} catch (e) {
copysuccess = false
}
return copysuccess
}
function selectAndCopy() {
selectCellText();
copySelectionText();
}
document.getElementById('tbl1').onclick = selectAndCopy;