Javascript: execCommand ("removeformat") does not split the h2 tag

I am setting up the wysiwyg editor and I am trying to create an icon that will strip the selected h2 text.

In the previous version, the team worked perfectly:

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

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

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

I think I will have to give up execCommand and find another way, but I also think that it will be much more than just one line of code! I would be grateful for the suggestions.

+6
source share
3 answers

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

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

There is also another solution to get the closest parent element from the selected text, then you can expand it, note that this may 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+ 
+4
source

This is in line with the proposed W3C editing API . It contains a list of formatting elements, but no H# elements are specified. They are considered structural, not just formatting. It makes no sense to remove these tags than to delete UL or P

+3
source

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

example from this 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); 
+1
source

All Articles