Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select all text in contenteditable div?

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?

like image 359
Lucas Avatar asked Sep 03 '12 07:09

Lucas


People also ask

How do I select all text in a div?

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.

How do I get selected text Contenteditable?

text) { return selection. text; } return false; } return false; }; $("#content-create-partial"). bind("mouseup", function(){ var text = getSelected(); if(text) { console. log(text); } else{ console.

What is Contenteditable div?

Definition and Usage The contenteditable attribute specifies whether the content of an element is editable or not.


1 Answers

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.

like image 95
Tom Oakley Avatar answered Sep 24 '22 02:09

Tom Oakley