7

I'm tweaking a wysiwyg editor, and I'm trying to create an icon which will strip selected text of h2.

In a previous version, the following command worked perfectly:

oRTE.document.execCommand("removeformat", false, "");

But in the current version, although that command successfully removes from selected text such tags as bold, underline, italics, it leaves the h2 tag intact.

(Interestingly enough, execCommand("formatblock"...) successfully creates the h2 tag.)

I'm thinking that I'm going to have to abandon execCommand and find another way, but I'm also thinking that it will be a lot more than just 1 line of code! Would be grateful for suggestions.

3 Answers 3

8

You can change your format to div, it's not the best solution but it works and it's short:

document.execCommand('formatBlock', false, 'div')

There is also this other solution to get the closest parent from selected text then you can unwrap it, note that this can be some tag like <b>:

var container = null;
if (document.selection) //for IE
    container = document.selection.createRange().parentElement();
else {
    var select = window.getSelection();
    if (select.rangeCount > 0)
        container = select.getRangeAt(0).startContainer.parentNode;
}
$(container).contents().unwrap(); //for jQuery1.4+
5

This is in accordance with the proposed W3C Editing APIs. It has a list of formatting elements, and the H# elements are not listed. These are considered structural, not simply formatting. It doesn't make any more sense to remove these tags than it would to remove UL or P.

3
  • I guess I should have made my question more explicit: so what do I do now?
    – oyvey
    Commented Dec 26, 2012 at 10:35
  • If you need to remove specific elements, use explicit DOM manipulation functions to search for them and remove them. jQuery can help reduce the number of lines of code.
    – Barmar
    Commented Dec 26, 2012 at 13:43
  • 2
    I posted here to get more detailed answers than that. And keeping in mind that I need to remove the h2 tag only from the currently highlighted text.
    – oyvey
    Commented Dec 27, 2012 at 15:20
1

I think you can use the Range object. you can find it from Professional JavaScript for Web Developers 3rd Edition. chapter 12(12.4) and chapter 14(14.5) ...

an example from that book:

var selection = frames["richedit"].getSelection();

var selectedText = selection.toString();

var range = selection.getRangeAt(0);

var span = frames["richedit"].document.createElement("span");
span.style.backgroundColor = "yellow";
range.surroundContents(span);

Not the answer you're looking for? Browse other questions tagged or ask your own question.