Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select div text on button click?

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/

like image 716
rajagopalx Avatar asked Dec 09 '22 02:12

rajagopalx


2 Answers

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>
like image 89
Pierre Irani Avatar answered Dec 17 '22 22:12

Pierre Irani


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);
    }
}
like image 43
Max Avatar answered Dec 17 '22 23:12

Max