4

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/

rajagopalx
  • 3,012
  • 9
  • 41
  • 52

3 Answers3

17

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>
Pierre Irani
  • 805
  • 5
  • 19
  • 2
    this might fail if you have text selected on Chrome. I had to add this: `window.getSelection().empty();` before the `addRange` call to avoid an error in console `Discontiguous selection is not supported.` – Jochen Bedersdorfer Mar 04 '17 at 02:51
1
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);
    }
}
Max
  • 336
  • 1
  • 12
  • [Deprecation] The behavior that Selection.addRange() merges existing Range and the specified Range was removed. See https://www.chromestatus.com/features/6680566019653632 for more details. – atilkan Nov 12 '17 at 18:40
-3

I hope it will help you.

html code

<div id="divid">Hello This div content have to be select. </div>
        <button id="hit"> Select Div</button>

demo.js

$(document).ready(function(){
    $('#hit').on('click', function(){
        var sav = $('#divid').html();
        alert(sav);
    });
});