In JavaScript, it's possible to programmatically select text in an input
or textarea
element. You can focus an input with ipt.focus()
, and then select its contents with ipt.select()
. You can even select a specific range with ipt.setSelectionRange(from,to)
.
My question is: is there any way to do this in a contenteditable
element too?
I found that I can do elem.focus()
, to put the caret in a contenteditable
element, but subsequently running elem.select()
doesn't work (and nor does setSelectionRange
). I can't find anything on the web about it, but maybe I'm searching for the wrong thing...
By the way, if it makes any difference, I only need it to work in Google Chrome, as this is for a Chrome extension.
You can add the contenteditable="true" HTML attribute to the element (a <div> for example) that you want to be editable. If you're anticipating a user to only update a word or two within a paragraph, then you could make a <p> itself editable.
The contenteditable global attribute is an enumerated attribute indicating if the element should be editable by the user. If so, the browser modifies its widget to allow editing.
Answer: Use the HTML5 contenteditable Attribute You can set the HTML5 contenteditable attribute with the value true (i.e. contentEditable="true" ) to make an element editable in HTML, such as <div> or <p> 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With