JavaScript document.execCommand remove formatBlock formatting?

13,240

Solution 1

I suppose document.execCommand('removeFormat',false,false) would do it?

Issuing document.execCommand('formatBlock', false, 'div') on the <h1>-block will remove the <h1>-tag and replace it with a <div>-tag 1. Would that be viable?

1 If you're not using IE that is

Solution 2

I had the same problem where I need to delete the h1 tag wrapping my text.

What I did was get the parent node of the selected text:

var elem_parent_node = window.getSelection().getRangeAt(0).startContainer.parentNode;

And then check if it's nodeName is "H1"; if yes, then store the selected text in a selected_text variable and then delete the node itself:

elem_parent_node.remove();

Then,

document.execCommand('insertText', false, select_text);

Solution 3

I clear the effect of h1 using this:

document.execCommand('formatBlock', false, 'p');

You have changed its format to h1, so we can change it back to normal paragraph format in the same way.
If your put each paragraph in a <div> , you can also use this:

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

to set the format to the same as other blocks.

Share:
13,240
Greg
Author by

Greg

Updated on July 28, 2022

Comments

  • Greg
    Greg almost 2 years

    If I format a piece of text on a page like this:

    document.execCommand('formatBlock', false, 'h1');
    

    What do I do to remove this formatting?