YeppThat'sMe
YeppThat'sMe

Reputation: 1862

Respect HTML tags inside an editable DIV

i'm trying to realize a very simple kind of wysiwyg javascript editor.

What i have: I know, the current Javascript doesn't work by hitting the button…

   wrapText = function(replacementText) {
          var range, sel;
          if (window.getSelection) {
            sel = window.getSelection();
            if (sel.rangeCount) {
              range = sel.getRangeAt(0);
              range.deleteContents();
              return range.insertNode(document.createTextNode(replacementText));
            } else if (document.selection && document.selection.createRange) {
              range = document.selection.createRange();
              return range.text = replacementText;
            }
          }
        };

<a id="bold-btn">Make it Bold!</a>
<div id="editit" contenteditable="true"></div>

Now, if you mark/highlight some text inside your editable div and hit the Make it Bold - Button. The selected text will be wrapped within a <b/> tag.

The problem is that the output seems like this:

This is a sample text with a <b>bold<b/> word.

instead of:

This is a sample text with a bold word.

Any idea?

Upvotes: 0

Views: 802

Answers (1)

Adam Sanderson
Adam Sanderson

Reputation: 490

You're trying too hard ;)

What your code is doing is creating a text node, which means the contents will be text instead of being treated as html. You can just use execCommand for this instead.

For instance, "Make it Bold" just needs to call document.execCommand('bold'). You can look at Mozilla's docs for execCommand for more details.

For a really small example, take a look at the demo for wysiwyg, and then look at index.js for some ideas, or just use the library yourself.

Upvotes: 1

Related Questions