Before this is flagged as a duplicate, I want you to realize that no one has actually provided a good answer for this specific question. In select all text in contenteditable div when it focus/click, the accepted answer and Tim Down's answer are both not helpful, as they only work when the element is already focused. In my case, I want all the text in the contenteditable div to be selected after the click of a button, even if the div was not focused beforehand.
How could I do this?
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.
text) { return selection. text; } return false; } return false; }; $("#content-create-partial"). bind("mouseup", function(){ var text = getSelected(); if(text) { console. log(text); } else{ console.
Definition and Usage The contenteditable attribute specifies whether the content of an element is editable or not.
I used some code from this thread to come up with my answer. It's 100% jQuery as you asked for as well. Hope you like it :)
jQuery.fn.selectText = function(){ var doc = document; var element = this[0]; console.log(this, element); if (doc.body.createTextRange) { var range = document.body.createTextRange(); range.moveToElementText(element); range.select(); } else if (window.getSelection) { var selection = window.getSelection(); var range = document.createRange(); range.selectNodeContents(element); selection.removeAllRanges(); selection.addRange(range); } }; $("button").click(function() { $("#editable").selectText(); });
jsfiddle link.
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