Select All Text (Div/Pre)
Make sharing easy. This script allows users to highlight an entire block of static text (like a code snippet or paragraph) with a single button click.
Code Snippet:
function helloWorld() {
console.log("Hello!");
return true;
}
Copy the Script
<script>
function selectText(containerid) {
if (document.selection) { // IE
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(containerid));
range.select();
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementById(containerid));
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
}
</script>
<div id="myDiv">Text to select.</div>
<button onclick="selectText('myDiv')">Select</button>
Frequently Asked Questions
Inputs use `element.select()`. Non-input elements (div, span, pre) require the Selection and Range APIs (`window.getSelection()`).
This script selects the text. You can add `document.execCommand('copy')` to copy it immediately after selection.
Yes. It highlights the text block, bringing up the native 'Copy/Share' menu on iOS and Android.