-1

I'm trying to make it so I can edit an iframe and be able to set selected text to bold. As you can see in the text below.

enter image description here

Now, I will explain how I am stuck, first of all here is some code:

var sel = $iFrame.get(0).contentWindow.getSelection();
if (sel.rangeCount) {
   var text = sel.toString();
   var range = sel.getRangeAt(0);
   var parent = range.commonAncestorContainer;
   if (parent.nodeType != 1) {
      parent = parent.parentNode;
   }

   if (range.startOffset > 0) {
     // change at offset
   } else {
     // change at beginning
   }
}

So far I have acquired the parent node. But I'm struggling with how I can replace the content within the parent node with the new code including the tags. I also need it to consider that other text might already be bold and words might be repeated so i need it to make the exact highlighted option bold.

Also be able to reverse it to remove the bold from the selected text.

How can I proceed from this?

Community
  • 1
  • 1
mdixon18
  • 1,199
  • 4
  • 14
  • 35

1 Answers1

0

You don't want to insert tags yourself; just let the browser do it with the built-in commands. As long as the user has text selected in a contenteditable document, just running this function call will turn it bold:

document.execCommand('bold', false, null)

This works on practically every browser. Other commands and full documentation can be found here: https://developer.mozilla.org/en-US/docs/Web/API/document/execCommand

Pluto
  • 2,900
  • 27
  • 38
  • Yeah I have seen this method, but i would like to say make it so if i have italics, bold and underline that they fall into 1 tag so possibly, selected text as I am looking to create a HTML editor and be able to allow them to add custom classes too if they wanted too. So if possible I would like to be able to take the offset, remove tags to find it, add tags and put other tags back in if possible :/ or something like this. – mdixon18 Jul 20 '15 at 20:11
  • 1
    If you want to combine tags because you want to reduce the HTML, then that's going to be difficult. If you simply want to use styles or classes so you can do other things with them, you can use the regular editor commands, then update each one to add your CSS/class. See this answer as an example: http://stackoverflow.com/questions/28197356/changing-font-size-options-on-wysiwyg-editor/28199023#28199023 – Pluto Jul 20 '15 at 21:44