Trying to make a personal HTML editor. With textarea, everything works as it should: ( CodePen-1 )
If nothing is selected, tags are added simply at the end of the printed text. And if you select the text - when you click on the button, the text is placed inside the tags.

<button title="division" class="tag" onclick="tag('<div>','</div>');">div</button> <textarea id="form"></textarea> 

Js:

 function tag(a,b){ var x = document.getElementById('form'); x.focus(); var value = $("#form").val(); var start=x.selectionStart; var end=x.selectionEnd; var selected = a + value.substr(start,end-start) + b; $("#form").val( value.substr(0,start) + selected + value.substr(end) ); } 

But the interior of the Textarea is impossible to paint or somehow select, so there is a need to make an editable div in which you can already highlight keywords or tags. But selectionStart and selectionEnd do not work here ( CodePen-2 ):

 <button title="division" class="tag" onclick="tag('<div>','</div>');">div</button> <div id="form" contenteditable="true"></div> 

Js:

 function tag(a,b){ var x = document.getElementById('form'); var value = $("#form").text(); var start = x.selectionStart; var end = x.selectionEnd; var selected = a + value.substr(start,end-start) + b; $('#form').text( value.substr(0,start) + selected + value.substr(end) ); x.focus(); } 

The spear method did not work and it is not clear what I am doing wrong. Apparently you just need to know ...

  • 2
    Textarea and Contenteditable - what's the difference? - in that these are different elements, one text field, the second - no - Grundy

1 answer 1

The selectionStart and selectionEnd properties are declared directly in the HTMLTextAreaElement and HTMLInputElement .

As in the case of a contenteditable element, there is a div - these properties are absent.

To get the selected text, you can use the getSelection function getSelection

 function tag(a, b) { var x = document.getElementById('form'); var value = $("#form").text(); var selection = window.getSelection().getRangeAt(0); var start = selection.startOffset; var end = selection.endOffset; var selected = a + value.substr(start, end - start) + b; $('#form').text(value.substr(0, start) + selected + value.substr(end)); x.focus(); } 
 .tag { width: 90px; border: 3px solid #800; color: #800; background-color: white; margin: 0 0 10px 0; padding: 5px; } #form { width: 800px; height: 150px; background: rgb(255, 222, 159); font-size: 18px; border: 2px solid #800 } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button title="division" class="tag" onclick="tag('<div>','</div>');">div</button> <br> <div id="form" contenteditable="true"></div>