JQuery JavaScript Select All Text In Content Editable Div

by Pritom K Mondal

HTML

<div class="sticky_editor" style="" contentEditable="true">
    JQuery JavaScript Select All Text In Content Editable Div.<br/>Thanks.
    <p>This is p tag</p>
</div>
<button>Check</button>

CSS

.sticky_editor {
    background-color: #FFFFCC;
    background-position: -1px top;
    background-repeat: repeat;
    line-height: 20px;
    min-height: 113px;
    border: 1px solid #E7E7E7;
    box-shadow: 0 1px 0 rgba(0, 0, 0, 0.3) inset;
    transition: border 0.2s linear 0s, box-shadow 0.2s linear 0s;
    font-family: monospace;
    padding: 12px;
    overflow: auto;    
}

JavaScript

jQuery.fn.selectText = function(){
   var doc = document;
   var element = this[0];
   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() {
    $(".sticky_editor").selectText();
});