I've got contenteditable div as below.
<div style=" border:solid 1px #D31444" contenteditable="true">12 some text...</div>
What I need is, when I click on the div, all the text will automatically get selected. Can you give me solution please?
To select all text inside an element such as DIV, we can simply use JavaScript document. createRange() method to create a range, and than using range. selectNodeContents() we can set node range (start and end), after which use selection. addRange() to select the range of the element.
Changing your tabIndex to >= 0 will let you focus on the elements. If you need to do it dynamically, you can just add a tabindex >= 0 to your element in the event listener.
contenteditable="false" Indicates that the element is not editable. contenteditable="inherit" Indicates that the element is editable if its immediate parent element is editable.
This will do it. The timer is there for Chrome and Safari because in those browsers, the native browser behaviour that selects the whole element seems to trigger after the focus event, thereby overriding the effect of the selection code unless postponed until after the focus event:
var div = document.getElementById("editable"); div.onfocus = function() { window.setTimeout(function() { var sel, range; if (window.getSelection && document.createRange) { range = document.createRange(); range.selectNodeContents(div); sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } else if (document.body.createTextRange) { range = document.body.createTextRange(); range.moveToElementText(div); range.select(); } }, 1); };
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.
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