Select all DIV text with single mouse click on HTML button

To totally unlock this section you need to Log-in


The following code can be used in a HTML page to select, for example with an onClick event handler, the whole content of a DIV container:

<script type="text/javascript">
function selectText(containerid) {
        if (document.selection) {
            var range = document.body.createTextRange();
        } else if (window.getSelection) {
            var range = document.createRange();

We can call this code, for example, directly by clicking on the text inside a DIV, as following:

<div id="selectable" onclick="selectText('selectable')"><div>

Or we can use a simple button to do the same (outside the target DIV):

<input type="button" onclick="selectText('targetDIV');" id="selectable" value="Select the DIV">

To fix the "Discontiguous selection is not supported." error that could raise on Chrome or Firefox we have included the window.getSelection().removeAllRanges(); in the above code to be sure that every time the function selectText is called the range previously already selected is reset.