Reputation: 191
How can i select the whole HTML document using javascript.
I have tried these functions but dint work!!
function SelectAll()
{
document.body.focus();
document.body.select();
}
function SelectAll()
{
document.body.select();
}
My whole code is
<head>
<script type="text/javascript">
function SelectAll()
{
document.body.focus();
document.body.select();
}
</script>
</head>
<body>
<div>LaLa, Lala, laLa , lala, lalala, tralala, some other text</div>
<br />
<input type="text" id="findField" value="lala" size="20" />
<button onclick="SelectAll();">Find!</button>
</body>
Upvotes: 7
Views: 9584
Reputation: 13
You can write it like this
(function() {
function selectText(element) {
var doc = document
, text = element
, range, selection
;
if (doc.body.createTextRange) { //ms
range = doc.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) { //all others
selection = window.getSelection();
range = doc.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
preTags = document.getElementsByTagName('document.body');
for(var i=0;i<preTags.length;i++) {
preTags[i].onclick = function() {selectText(this)};
}
})();
Upvotes: 0
Reputation: 1
document.execCommand("selectAll");
https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand#Commands
Upvotes: -1
Reputation: 131
To select all text inside an element use this simple code. It will highlight the entire element / tag area with yellow colour and select text inside it on single click.
document.onclick = function(event) {
var range, selection;
event.target.style.backgroundColor = 'yellow';
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(event.target);
selection.removeAllRanges();
selection.addRange(range);
};
To select all text in the entire document you can modify this code as shown below:
document.onclick = function(event) {
var range, selection;
var doc = document.body;
doc.style.backgroundColor = 'yellow';
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(doc);
selection.removeAllRanges();
selection.addRange(range);
};
Upvotes: 1
Reputation: 736
Simplest way to do this.
$('input[type=button]').click( function() {
$("#t1").select();
});
Upvotes: 0
Reputation: 2716
Via Satya-Weblog:
(function() {
function selectText(element) {
var doc = document
, text = element
, range, selection
;
if (doc.body.createTextRange) { //ms
range = doc.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) { //all others
selection = window.getSelection();
range = doc.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
preTags = document.getElementsByTagName('document.body');
for(var i=0;i<preTags.length;i++) {
preTags[i].onclick = function() {selectText(this)};
}
})();
Upvotes: 4