How do you insert HTML into a QuillJS?

Viewed 35831

Is it possible to insert raw HTML into a Quill? I've been searching the documentation but couldn't find anything.

If it's not possible, can I at least convert HTML into a Quill Delta?

The reason I need this is because I am grabbing the raw HTML of the text taken from Quill, so I can view it later in HTML style. Have I been doing everything wrong, and need to keep a Delta version of it as well?

7 Answers

On version 1.3.6, You can use Quill.setContents(value) method.

And insert your new HTML like this:

const value = `<h1>New content here</h1>`
const delta = quill.clipboard.convert(value)

quill.setContents(delta, 'silent')

Quill documentation: https://quilljs.com/docs/api/#setcontents

Another way to insert HTML into Quill is by using vanilla JavaScript.

You can set your html to a variable, such as htmlToInsert.

Then target the contenteditable div created by Quill, by getting it by its class, ql-editor.

Finally, set the innerHTML of that div to the HTML you want to insert.

For example:

var htmlToInsert = "<p>here is some <strong>awesome</strong> text</p>"
var editor = document.getElementsByClassName('ql-editor')
editor[0].innerHTML = htmlToInsert

There is better way to do this:

const htmlMurkup = '<p>Good</p>'
let quill = new Quill()
quill.container.firstChild.innerHTML = htmlMurkup

I believe the most straight forward way is this:

quill.root.innerHTML = '<p>HTML Goes Here</p>'

You can also obtain the HTML from this property as well.

If you aren't getting the desired output. It could be because your html content is encoded.

Use this to convert it.

let realHTML = $('<textarea />').html("&lt;p&gt;&lt;strong&gt;Hello&lt;/strong&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;").text();
console.log(realHTML);

This code will output

<p><strong>Hello</strong></p>

After this you can use this command to set the html content in quill editor

quill.root.innerHTML = realHTML;

or even this:

let initialContent = quill.clipboard.convert(realHTML);
quill.setContents(initialContent, 'silent');

Its proper your html is in the real html format before setting the value on quill. Else the html tags would be displayed verbally.

Just to add to @user1993629's answer, using quill.clipboard.dangerouslyPasteHtml(0, "raw html") will place the cursor at the end of the pasted content

Related