Search code examples
javascripthtmlcontenteditable

Content Editable Div, appending HTML causing issue. Every text typed after programatically appending HTML gets added to the last HTML tag


enter image description hereI am trying to make a content editable div that can be used to generate message templates for an app. Users can append placeholders for fields like names to a template by hitting a button. The placeholders can be removed by hitting an 'x' on them as well. Here's the working snippet.

var removePlaceholder = function(e){
  e.parentNode.parentNode.removeChild(e.parentNode);
}

var appendPlaceHolder = function(field){
  var e = document.getElementById("t");
  e.innerHTML += ('<span class="tag">{'+field+'}<span onclick=removePlaceholder(this) class="remove">x</span></span>')
}
.tag {
  background-color : blue;
  color : white;
}
.remove {
  color : red
}
<div id="t" contenteditable="true">Hello</div>

<button onclick=appendPlaceHolder("first_name")>Add first name</button>

The contenteditable part works just fine. But after I've added a placeholder using my appendPlaceHolder function, everything I type seem to get appended to the last inserted HTML element.

How can I prevent this. I have closed the tag properly. Is there any way to change this behaviour.

To recreate issue, run the snippet and hit the "Add First Name" Button, then continue typing in the area.

Update

Have added image to explain the situation


Solution

  • What you can do is add a space after the placeholder has been appended:

    JavaScript

    var removePlaceholder = function(e){
      e.parentNode.parentNode.removeChild(e.parentNode);
    }
    
    var appendPlaceHolder = function(field){
      var e = document.getElementById("t");
      e.innerHTML += ('<span class="tag">{'+field+'}<span onclick=removePlaceholder(this) class="remove">x</span></span>&nbsp;')
    }
    

    Note: The &nbsp; which has been added at the end of the span just creates a space.

    Live Example

    JSFiddle