I am using the quill text editor in a javascript app and I need to retrieve the contents of the text editor as a string with the HTML included but the docs are a little sparse on this subject.
7 Answers
Depends what you want to get, here's an example showing a few ways:
http://codepen.io/k3no/pen/amwpqk
var delta = editor.getContents();
var text = editor.getText();
var justHtml = editor.root.innerHTML;
preciousContent.innerHTML = JSON.stringify(delta);
justTextContent.innerHTML = text;
justHtmlContent.innerHTML = justHtml;
-
-
2Hi, @AnjanaSilva. I'm just here to point out a very useful Quill repository.– LoaCommented Dec 30, 2019 at 16:16
-
Is it possible to get the returned
justHtml
to respect the new lines? I always seem to get everything back in one line. Commented Jan 20, 2020 at 2:16 -
But how to put it in a simple Input field in the HTML FORM? Thanks! Commented Feb 12, 2020 at 14:19
Quite simply by accessing the editor's innerHTML:
var quill = new Quill('#editor', {
theme: 'snow'
});
// ....
var editor_content = quill.container.innerHTML // or quill.container.firstChild.innerHTML could also work
Hope this helps!
-
24.container.innerHTML will get both the editor HTML and the content HTML. To get only the content HTML without the editor I use root.innerHTML Commented Feb 19, 2018 at 4:08
Hey all I was previously using the "innerHTML" method but this can lead to maintenance issues down the line.
Quill JS 2.0 makes Unordered Lists actually Ordered Lists (just styled as a UL) https://github.com/quilljs/quill/issues/3957, which then results in bad HTML in your DB. If you are saving the contents in the DB, and want the HTML to be formatted for other uses be sure to use
quill.getSemanticHTML()
This will return items appropriately. Hope this helps anyone using quill 2.0 or later
-
I'd give this 1000 upvotes if I could. Why have I never seen this before. Makes life so much much easier :) Thanks. Commented Jun 28 at 3:44
-
Argh! Back to the beginning again for me. It converts embeds to hyperlinks 🤦♂️ Commented Jun 29 at 4:33
if you want just what you written inside root.innerHTML
is better option because .container.innerHTML
give you bunch of other tags that is inside the .editor
class.
const myEditor = new Quill('#my-editor', {
//configuration
});
myEditor.root.innerHTML;
add if you want to get the text after change use on
event
myEditor.on('text-change', function(delta, oldDelta, source) {
//on change opration
});
This was great for getting the text from the editor and answers OP's question, but the text still wasn't showing up in the posted form. Others may come here with the same problem, so I'm posting the solution to that here.
I had to manually add the text from the editor to the form's dom.
document.getElementById('formSave').addEventListener('submit', validate);
function validate(e) {
let blogHtml = editor.root.innerHTML;
// do validations and do e.preventDefault() on fail, but if valid, then...
let input = document.createElement('input');
input.setAttribute('name', 'blog');
input.setAttribute('value', blogHtml);
input.setAttribute('type', 'text')
document.getElementById('formSave').appendChild(input);
}
This is so easy process, let me guide you.
initialize and config:
var quill = new Quill('#editor-container', {
modules: {
syntax: true,
toolbar: '#toolbar-container'
},
placeholder: 'Compose an epic...',
theme: 'snow',
readOnly: false,
});
Now get content on changing the editor data
quill.on('text-change', function(delta, source) {
var justHtml = quill.root.innerHTML;
document.getElementById('output-html').innerHTML = justHtml;
});
HTML code:
<div class="ql-snow">
<div class="ql-editor" id="output-html">
// the content goes here
</div>
</div>
I got it working with this, using React with Inertia. This is working code of creating a new post.
import { useEffect, useState, useRef } from "react";
import { Link, Head, usePage, useForm, router } from "@inertiajs/react";
import Authenticated from "../../../Layouts/Authenticated";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
export default function Post({ auth }) {
const { flash } = usePage().props;
const { photos } = usePage().props;
const { categories } = usePage().props;
const [editor, setEditor] = useState();
const editorRef = useRef(null);
const { data, setData, post, processing, errors } = useForm({
name: "",
slug: "",
description: "",
banner: "",
summary: "",
body: "",
category_id: null,
active: null,
});
function handleSubmit(e) {
e.preventDefault();
post(route("dashboard.posts.store"));
}
useEffect(() => {
setData("body", editor);
}, [editor]);
const modules = {
toolbar: [
[{ font: [] }, "header"],
[{ header: [1, 2, 3, false] }],
["bold", "italic", "underline", "strike"],
[{ script: "sub" }, { script: "super" }],
["blockquote", "code-block"],
[{ list: "ordered" }, { list: "bullet" }],
[{ indent: "-1" }, { indent: "+1" }, { align: [] }],
["link"],
]
}
return (
<>
<Authenticated user={ auth.user } header={"Dashboard :: Create Post"}>
<Head title="Dashboard :: Create Post" />
<form onSubmit={ handleSubmit }>
<div className="mx-auto w-full md:w-3/4 lg:w-1/2">
<div className="border-b border-gray-400 pb-4">
<ReactQuill
theme="snow"
className="mt-4"
modules={ modules }
onChange={ setEditor }
ref={ editorRef }
/>
{errors.body && <div className="text-md font-bold text-red-700">{ errors.body }</div>}
<label htmlFor="name" className="mt-4 block font-bold text-lg text-gray-700">Name</label>
<input
type="text"
id="name"
autoComplete="off"
placeholder="Enter a name"
onChange={e => setData("name", e.target.value)}
className="mt-1 block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
/>
{errors.name && <div className="text-md font-bold text-red-700">{ errors.name }</div>}
<label htmlFor="slug" className="mt-4 block font-bold text-lg text-gray-700">Slug</label>
<input
type="text"
id="slug"
autoComplete="off"
placeholder="Enter a slug"
onChange={e => setData("slug", e.target.value)}
className="mt-1 block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
/>
{errors.slug && <div className="text-md font-bold text-red-700">{ errors.slug }</div>}
<label htmlFor="description" className="mt-4 block font-bold text-lg text-gray-700">Description</label>
<input
type="text"
id="description"
autoComplete="off"
placeholder="Enter a description for search engines"
onChange={e => setData("description", e.target.value)}
className="mt-1 block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
/>
{errors.description && <div className="text-md font-bold text-red-700">{ errors.description }</div>}
<label htmlFor="category_id" className="mt-4 block font-bold text-lg text-gray-700">Categories</label>
<select
size="5"
id="category_id"
className="mt-1 block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
onChange={e => setData("category_id", e.target.selectedOptions[0].value)}>
<option value="">Select a Category</option>
{
categories.map((category) => (
<option key={ category.id } value={ category.id }>{ category.name }</option>
))
}
</select>
{errors.category_id && <div className="text-md font-bold text-red-700">{ errors.category_id }</div>}
<label htmlFor="photos" className="mt-4 block font-bold text-lg text-gray-700">Photos</label>
<select
size="10"
id="photos"
className="mt-1 block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm">
<option value="">Select a Photo</option>
{
photos.map((photo) => (
<option key={ photo.id } value={ photo.id }>{ photo.caption } / { photo.url }</option>
))
}
</select>
<label htmlFor="banner" className="mt-4 block font-bold text-lg text-gray-700">Banner</label>
<textarea
rows="6"
type="text"
id="banner"
autoComplete="off"
placeholder="Enter a banner"
onChange={e => setData("banner", e.target.value)}
className="mt-1 block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
/>
{errors.banner && <div className="text-md font-bold text-red-700">{ errors.banner }</div>}
<label htmlFor="summary" className="mt-4 block font-bold text-lg text-gray-700">Summary</label>
<textarea
rows="6"
type="text"
id="summary"
autoComplete="off"
placeholder="Enter a summary"
onChange={e => setData("summary", e.target.value)}
className="mt-1 block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
/>
{errors.summary && <div className="text-md font-bold text-red-700">{ errors.summary }</div>}
<textarea className="hidden" id="body" defaultValue={ editor } />
<div className="mt-4">
<input
type="checkbox"
id="active"
onChange={e => setData("active", e.target.value)}
className="me-4 rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500"
/>
<label htmlFor="active" className="font-bold text-md text-gray-700">Check, if this post is active</label>
</div>
<button disabled={ processing } className="mt-4 me-2 bg-transparent hover:bg-gray-500 text-gray-700 font-bold hover:text-white py-2 px-4 border border-gray-500 hover:border-transparent rounded">Create</button>
<Link href={route("dashboard.posts.index")} role="button" as="button" className="mt-4 bg-blue-700 hover:bg-blue-500 text-gray-700 font-bold text-white py-2 px-4 border border-blue-500 hover:border-transparent rounded">Cancel</Link>
</div>
</div>
</form>
</Authenticated>
</>
);
}
On the Laravel side of things I use this.
// etc,...
public function create()
{
return inertia('Dashboard/Post/Create', [
'categories' => $this->getCategoryService()->getRepository()->findWhere([
'active' => true,
]),
'photos' => $this->getPhotoService()->getRepository()->findWhere([])
]);
}
The package.json is below for completeness.
{
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"devDependencies": {
"@headlessui/react": "^2.1.2",
"@inertiajs/react": "^1.0.0",
"@tailwindcss/forms": "^0.5.3",
"@vitejs/plugin-react": "^4.2.0",
"autoprefixer": "^10.4.12",
"axios": "^1.7.4",
"laravel-vite-plugin": "^1.0",
"postcss": "^8.4.31",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"tailwindcss": "^3.2.1",
"vite": "^5.0"
},
"dependencies": {
"@emotion/react": "^11.13.3",
"@emotion/styled": "^11.13.0",
"@heroicons/react": "^2.1.5",
"@hookform/resolvers": "^3.9.0",
"@inertiajs/inertia": "^0.11.1",
"@mui/material": "^5.16.7",
"react-cropper": "^2.3.3",
"react-easy-crop": "^5.0.8",
"react-form-hook": "^0.0.1",
"react-image-crop": "^11.0.6",
"react-paginate": "^8.2.0",
"react-quill": "^2.0.0",
"react-toastify": "^10.0.5",
"yup": "^1.4.0"
}
}
For editing the post, it is the same except for the useEffect hook, a slight change and there are two hooks.
useEffect(() => {
setEditor(
editorRef.current.getEditor().clipboard.dangerouslyPasteHTML(0, entity.body)
);
}, []);
useEffect(() => {
setData("body", editor);
}, [editor]);
The first hook is when the page loads and the second hook when you use the editor it updates the form data.
-
1Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community? Commented Sep 6 at 5:03