Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: execCommand("removeformat") doesn't strip h2 tag

Tags:

javascript

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.

like image 370
oyvey Avatar asked Dec 25 '12 07:12

oyvey


2 Answers

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+
like image 128
shuji Avatar answered Sep 22 '22 04:09

shuji


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.

like image 33
Barmar Avatar answered Sep 22 '22 04:09

Barmar