Categories
JavaScript Answers

How to insert HTML at caret in a contenteditable div with JavaScript?

Spread the love

Sometimes, we want to insert HTML at caret in a contenteditable div with JavaScript.

In this article, we’ll look at how to insert HTML at caret in a contenteditable div with JavaScript.

How to insert HTML at caret in a contenteditable div with JavaScript?

To insert HTML at caret in a contenteditable div with JavaScript, we c an use the execCommand method.

For instance, we write

<iframe id="editor" src="contenu_editor_wysiwyg.php"> </iframe>

to add an iframe.

Then we write

const editor = document.getElementById("editor");
editor.contentDocument.designMode = "on";
editor.contentWindow.document.execCommand("insertHTML", false, "<br />");

to get the editor with getElementById.

And then we set designMode to 'on' so that we can insert HTML.

Then we insert the HTML at the caret of the iframe’s document by calling execuCommand with 'insertHTML' and the HTML to add.

Conclusion

To insert HTML at caret in a contenteditable div with JavaScript, we c an use the execCommand method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *