I would like to have users click a link, then it selects the HTML text in another element (not an input).
By "select" I mean the same way you would select text by dragging your mouse over it. This has been a bear to research because everyone talks about "select" or "highlight" in other terms.
Is this possible? My code so far:
HTML:
<a href="javascript:" onclick="SelectText('xhtml-code')">Select Code</a>
<code id="xhtml-code">Some Code here </code>
JS:
function SelectText(element) {
$("#" + element).select();
}
Am I missing something blatantly obvious?
This question is related to
javascript
jquery
function selectText(node) {_x000D_
node = document.getElementById(node);_x000D_
_x000D_
if (document.body.createTextRange) {_x000D_
const range = document.body.createTextRange();_x000D_
range.moveToElementText(node);_x000D_
range.select();_x000D_
} else if (window.getSelection) {_x000D_
const selection = window.getSelection();_x000D_
const range = document.createRange();_x000D_
range.selectNodeContents(node);_x000D_
selection.removeAllRanges();_x000D_
selection.addRange(range);_x000D_
} else {_x000D_
console.warn("Could not select text in node: Unsupported browser.");_x000D_
}_x000D_
}_x000D_
_x000D_
const clickable = document.querySelector('.click-me');_x000D_
clickable.addEventListener('click', () => selectText('target'));
_x000D_
<div id="target"><p>Some text goes here!</p><p>Moar text!</p></div>_x000D_
<p class="click-me">Click me!</p>
_x000D_
Here is a working demo. For those of you looking for a jQuery plugin, I made one of those too.
I have found a solution for this in this thread. I was able to modify the info given and mix it with a bit of jQuery to create a totally awesome function to select the text in any element, regardless of browser:
function SelectText(element) {
var text = document.getElementById(element);
if ($.browser.msie) {
var range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if ($.browser.mozilla || $.browser.opera) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
} else if ($.browser.safari) {
var selection = window.getSelection();
selection.setBaseAndExtent(text, 0, text, 1);
}
}