Justin Levine
Justin Levine

Reputation: 285

Javascript Inserting Element by char Ref into editable DIV with child elements

Right now I have an editable DIV. I have been able to get the char index fairly easy, but I am having trouble inserting it in the correct place. I can use splice to insert it, which works as long as there is no HTML elements. So how would I go about ignoring the tags? It seems like using a regular expression might be possible, but a little too much processing. It seems like I could use a Range, but I have a lot of trouble understanding JavaScript Ranges. Here is the basic idea:

<div class="toinsert" contenteditable="true">Some Text <strong>here</strong></div>

.

var charisat = 8; //SOME NUMBER

var dividedcontent = []; //DIVIDE CONTENT, BY RANGE OR REGEX

$('.toinsert').html(dividedcontent[0] + '<em>other text</em>' + dividedcontent[1]);

Upvotes: 0

Views: 37

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

Not sure if there a better way, but a crude way will be something like

var charisat = 8;
addContent($('<em>other text</em>'), charisat, $('.toinsert'))


function addContent($content, pos, $el) {
  $el.contents().each(function() {
    if (this.nodeType == Node.TEXT_NODE) {
      var text = $(this).text();
      if (text.length >= pos) {
        var $obj = $();
        $obj = $obj.add(document.createTextNode(text.substring(0, pos)));
        $obj = $obj.add($content);
        $obj = $obj.add(document.createTextNode(text.substring(pos)));
        $(this).replaceWith($obj);
        return;
      } else {
        pos -= text.length;
      }
    } else if (this.nodeType == Node.ELEMENT_NODE) {
      pos = addContent($content, pos, $(this));
    }
    return pos;
  })
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="toinsert" contenteditable="true">Some Text <strong>here</strong>
</div>

Upvotes: 1

Related Questions