The principle is as follows. After clicking on the button , the div was replaced with textarea and the message was sent.

 <div id="message" contenteditable="true"></div> <button id="bsmile">Добавить</button> $("#bsmile").click(function() { $('div#message').each(function() { $("#message").replaceWith(function(index, oldHTML) { return $("<textarea id='message' rows='3'>" + $(this).html() + "</textarea>") .html(oldHTML); }) }); }); 

But if in a div some kind of html code, for example, the picture <img src="/opacity.png" in the textarea it already looks like this &lt;img src="/opacity.png" . How to make a normal <img ?

  • If you are given an exhaustive answer, mark it as correct (the daw opposite the selected answer) - Mr. Black

2 answers 2

Everything in textarea has only a text property and cannot contain tags. There is a div with the attribute contenteditable='true'

 c = document.getElementById('content'); b = document.querySelectorAll('button'); b[0].onclick = function() { c.innerText = '<font color=red>Font</font>'; } b[1].onclick = function() { c.innerHTML = c.innerText; } b[2].onclick = function() { c.innerText = c.innerHTML; } 
 .content { background: #F4F4F4; max-width: 256px; height: 96px; padding: 16px 16px; outline: none; cursor: text; margin-bottom: 16px; } 
 <div id='content' class='content' contenteditable='true' placeholder='Контент'></div> <button>paste</button> <button>to html</button> <button>to code</button> 

  • I made an example of codepen.io/stopani/pen/dXYRor, that is, writing a div sign < , then after clicking on the add button, this div changes to textarea and through the inspector you can see that the sign is already such &lt; . How to make this sign < not changed? - steep
  • @ SergeyLapshin, all that is written in the div becomes a text, not an html element. In textarea can not be elements of html, only text. Explain clearly what should happen? - Mr. Black
  • I just need to send a picture in the comments. Completed the example codepen.io/stopani/pen/dXYRor - steep
  • @ SergeyLapshin, if I understood correctly: There is a div , there we insert <img src='/opacity.png'> and after that a picture should appear in the div instead of the text, right? - Mr. Black
  • Yes, but when the div changes to textarea, the text is received and the picture is sent with an error &lt;img src=" and is already displayed in the comment simply by the text because of this &lt; - steep

Colleagues, between

 <textarea ...> 

and

 </textarea> 

You can insert any text with tags, and this text will be perfectly displayed. Therefore, the following sequence of actions should be performed in the script:

  1. Calculate the innerHtml parent element for textarea.
  2. Replace with operations on the lines in it the line between

     <textarea ...> 

    and

     </textarea> 

    on the text you need with tags.

  3. innerHtml element of the textarea innerHtml new value.

And that's all ...