Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
37
rated 0 times [  43] [ 6]  / answers: 1 / hits: 18196  / 9 Years ago, tue, july 28, 2015, 12:00:00

I want to select the div content on click button.



HTML



 <div id=divid>Hello This div content have to be select. </div>
<button onclick=selectText(divid);> Select Div</button>


JS



   function selectText(divid) {
if (document.selection) {
var div = document.body.createTextRange();

div.moveToElementText(document.getElementById(divid));
div.select();
}
else {
var div = document.createRange();
div.setStartBefore(document.getElementById(divid));
div.setEndAfter(document.getElementById(divid));

window.getSelection().addRange(div);
}

}


https://jsfiddle.net/rajagopalx/xds4y0en/


More From » html

 Answers
35

Try the below @Rajagopal Subramanian





 function selectText(containerid) {
if (document.selection) {
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().addRange(range);
}
}

<div id=divid>Hello This div content have to be select.</div>
<button onclick=selectText('divid')>Select</button>




[#65644] Sunday, July 26, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zayne

Total Points: 366
Total Questions: 98
Total Answers: 98

Location: India
Member since Wed, Aug 4, 2021
3 Years ago
;