0

I try to build my own WYSIWYG editor in javascript. Most of the buttons are quite simple (as long as document.execCommand has a commandId).

But how to implement a code option like in StackOverflow editor.

What I tried:

document.execCommand('formatBlock', '<pre><code>')

Unfortunately, it is not working. What I'm doing wrong?

1

1 Answer 1

1

The <code> tag is not part of the list of supported tags for formatBlock. You can however insert a <pre> tag by using:

document.execCommand('formatBlock', false, '<pre>');

You can check the w3c documentation for a list of supported tags (it depends on the browser).

If you do not care about IE, you can use the insertHTML option, combined together with document.getSelection(), like so:

document.execCommand('insertHTML', false, `<pre><code>${document.getSelection()}</code></pre>`)

Or you could implement the functionality yourself. As pointed out by others, document.execCommand is now obsolete, so it might be your safest option, depending on which browsers you need to support.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. Didn't noticed that. Looks like there is also no alternative yet right?
Actually if you do not care about IE there is a way to do it with insertHTML so I will update my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.