Programmatically Select Text in a Contenteditable HTML Element

Programmatically select text in a contenteditable HTML element?

If you want to select all the content of an element (contenteditable or not) in Chrome, here's how. This will also work in Firefox, Safari 3+, Opera 9+ (possibly earlier versions too) and IE 9. You can also create selections down to the character level. The APIs you need are DOM Range (current spec is DOM Level 2, see also MDN) and Selection, which is being specified as part of a new Range spec (MDN docs).

function selectElementContents(el) {
var range = document.createRange();
range.selectNodeContents(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}

var el = document.getElementById("foo");
selectElementContents(el);

select all text in contenteditable div when it focus/click

Try this:

<div style="border:solid 1px #D31444"
contenteditable="true"
onclick="document.execCommand('selectAll',false,null)">12 some text...</div>

Update: Note that document.execCommand is now deprecated although it still works.

How can I programmatically simulate typing in a contenteditable HTML element?

You could use Document.execCommand() with the insertText command, which will also fire input events automatically:

const editor = document.getElementById('editor');
editor.oninput = (e) => console.log('Input');
setTimeout(() => { editor.focus(); document.execCommand('insertText', false, 'Inserted text...\n\n');}, 1000);
body {  display: flex;  flex-direction: column;  font-family: monospace;}
#editor { box-shadow: 0 0 32px 0 rgba(0, 0, 0, .125); border-radius: 2px; min-height: 64px; padding: 16px; outline: none;}
<div id="editor" contenteditable="true"></div>

Programmatically select text in a contenteditable HTML element?

If you want to select all the content of an element (contenteditable or not) in Chrome, here's how. This will also work in Firefox, Safari 3+, Opera 9+ (possibly earlier versions too) and IE 9. You can also create selections down to the character level. The APIs you need are DOM Range (current spec is DOM Level 2, see also MDN) and Selection, which is being specified as part of a new Range spec (MDN docs).

function selectElementContents(el) {
var range = document.createRange();
range.selectNodeContents(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}

var el = document.getElementById("foo");
selectElementContents(el);

is there a way to programatically select all in a mobile web input textbox or contenteditable area?

found the answer in this post Programmatically select text in a contenteditable HTML element?

$scope.focusWhy = function($event) {
var el = $event.target;
var range = document.createRange();
range.selectNodeContents(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
};



Related Topics



Leave a reply



Submit