It is pretty easy to select all text inside an <input> or a <textarea> by using select() method like so:
document.querySelector('#exampleInput').select();
But how about selecting text inside elements other than <input> and <textarea>, such as <div>, <p>, and <pre>? Well, we can use the Selection API to select or deselect text inside these elements. For supporting old browsers that do not support Selection API, such as Internet Explorer 8 and below, we use fallbacks as shown in the functions below.
This function illustrates how to programmatically select all text inside any HTML element.
function selectText(element) { if (/INPUT|TEXTAREA/i.test(element.tagName)) { element.focus(); if (element.setSelectionRange) { element.setSelectionRange(0, element.value.length); } else { element.select(); } return; } if (window.getSelection) { // All browsers, except IE <=8 window.getSelection().selectAllChildren(element); } else if (document.body.createTextRange) { // IE <=8 var range = document.body.createTextRange(); range.moveToElementText(element); range.select(); } }
You can use the following function if you want to programmatically clear all selection.
function deselectAll() { var element = document.activeElement; if (element && /INPUT|TEXTAREA/i.test(element.tagName)) { if ('selectionStart' in element) { element.selectionEnd = element.selectionStart; } element.blur(); } if (window.getSelection) { // All browsers, except IE <=8 window.getSelection().removeAllRanges(); } else if (document.selection) { // IE <=8 document.selection.empty(); } }
Demo
Click the 'Run Demo' button below to select text inside a <div> element and deselect automatically after 2 seconds.
Click the 'Run Demo' button below to select text inside a <textarea> and deselect automatically after 2 seconds.