Search code examples
jqueryhtmlcontenteditable

How to get desired html from a contentEditable div


$('#parent').on('input', function(){
  let a = $(this).html();
  console.log(a);
});
.parent{
  background:gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='parent' id='parent' contentEditable>
  lorem ipsum
</div>

Place the cursor at the end of text and press Enter.
In console I'm expecting just <br> and not open and closed div tags.

Now, let's say I want a horizontal rule. Type <hr>
Result - <div>&lt;hr&gt;</div>

And of course when I place this value in a database (php, mysql) and getting this data back - there is no horizontal rule, just <hr> tag literally.

How to get desired html like this:

<br>  
<hr>

Solution

  • Something like this?

    $(function() {
      $('#parent').on('input', function() {
        // Retrieve the HTML-decoded content and log it
        let content = $('<textarea>')
          .html($(this).html())
          .text().trim()
          .replace(/<br><br>$/, '<br>');
        console.log(content);
      });
    
      $('#parent').on('keydown', function(e) {
        // Catch Enter key and insert <br>'s manually
        if (e.which === 13) {
          document.execCommand('insertHTML', false, '<br><br>');
          e.preventDefault();
        }
      });
    })
    .parent {
      background: gold;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div id="parent" class="parent" contenteditable>
      lorem ipsum
    </div>