I have an element that looks as following (https://jsfiddle.net/e176dosp/1/):
<button>
My Button
<table>
<thead align="left">
<tr>
<th>Category</th>
<th>Value</th>
</tr>
</thead>
<tbody align="left">
<tr>
<td>Soil group</td>
<td>Cambisols</td>
</tr>
</tbody>
</table>
</button>
I would like to be able to have the table element be separate from the button, meaning that I can click on the My Button text to press the button but also select the text from the table below, while still having the table be part of the button class. I have tried to find ways with javascript and css to "undo" the button class in the table element, or to find classes that override the button onclick behaviour but only found solutions on how to remove css classes that are not inbuilt, such as button or table.
CodePudding user response:
From what I gather, OP requests that a button (separate from the table) when clicked will select the text of the table. I suspect the ultimate goal is to have that button copy the text of the table to clipboard. If so, review the following example.
Details commented in example
/**
* @desc Copy the text of a given tag to the clipboard.
* @param {string<CSSString>/object<DOM>} selector - The
* HTML element to extract text from
* @param {boolean} pre - Option to copy text preformatted
* false (@default) - text is partially formatted
* true - text is preformatted
*/
function textCopy(selector, pre = false) {
let target = typeof selector == "string" ? document.querySelector(selector) : selector;
let text = !pre ? target.innerText : target.textContent;
navigator.clipboard.writeText('');
navigator.clipboard.writeText(text.normalize());
}
document.querySelector('button').onclick = function() {
textCopy('table');
}
table {
width: 50%;
text-align: left
}
td {
border: 1px solid #000
}
<button>Copy</button>
<table>
<thead>
<tr>
<th>Category</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>Soil group</td>
<td>Cambisols</td>
</tr>
</tbody>
</table>
<textarea rows='3' cols='30' placeholder='Paste Here'></textarea>
CodePudding user response:
Maybe using the user-select
property.
function fun1(e) {
e.stopPropagation();
}
function fun2(e) {
e.stopPropagation();
console.log("My Button");
}
button {
padding: 1px 0;
padding-bottom: 0;
}
.sel {
background-color: red;
-moz-user-select: text;
-webkit-user-select: text;
-ms-user-select: text;
user-select: text;
padding: 0 3px;
}
<button onclick="fun2(event)">
My Button
<table onclick="fun1(event)">
<thead align="left">
<tr>
<th>Category</th>
<th>Value</th>
</tr>
</thead>
<tbody align="left">
<tr>
<td>Soil group</td>
<td>Cambisols</td>
</tr>
</tbody>
</table>
</button>