Select all DIV text with single mouse click on HTML button


To totally unlock this section you need to Log-in


Login

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) {
	window.getSelection().removeAllRanges();
        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);
        }
    }
</script>

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

<div id="selectable" onclick="selectText('selectable')">http://example.com/page.htm<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.