Reputation: 553
How to get HTML of the selected text in ckeditor 5?
In ckeditor 4 there is getHTML() method. What is the analog in the 5th version?
Upvotes: 0
Views: 3614
Reputation: 46
Using DataController#stringify and getSelectedContent as Alexandros Kyriakos suggested, it can also be done like this:
let sHtmlSelection = this.editor.data.stringify(this.editor.model.getSelectedContent(this.editor.model.document.selection));
Upvotes: 2
Reputation: 31
You can use DataController#stringify to stringify your HTML from document's fragment using the getSelectedContent
import getSelectedContent from "@ckeditor/ckeditor5-engine/src/model/utils/getselectedcontent";
export default class CK5Utils{
static getSelectedHtml(ed) {
const {model, data, model:{document:{selection}}} = ed;
const range = selection.getFirstRange();
if (range.end.isEqual(range.start)) {
return '';
}
const selected = getSelectedContent(model, selection);
return data.stringify(selected);
}
}
Upvotes: 3
Reputation: 48600
You can grab the selected text within a range, but to get the HTML, it is a bit more tricky.
I was able to grab the name
of the parent
and run the value through a switch
statement.
Note: The code below has been adapted from here: "Get the highlighted/selected text in CKEDITOR 5"
const resultArea = document.querySelector('.selected');
let globalEditor;
ClassicEditor
.create(document.querySelector('#editor'))
.then(editor => globalEditor = editor)
.catch(error => console.error(error));
const formatNode = (node) => {
switch (node.parent.name) {
case 'heading1' : return `<h1>${node.data}</h1>`;
case 'heading2' : return `<h2>${node.data}</h2>`;
case 'heading3' : return `<h3>${node.data}</h3>`;
case 'paragraph' : return `<p>${node.data}</p>`;
default : return '';
}
};
const getSelectedHTML = (editor) =>
[...editor.model.document.selection.getFirstRange().getItems()]
.filter(node => node.data)
.map(formatNode)
.join('\n');
document.querySelector('.btn').addEventListener('click', e => {
resultArea.value = getSelectedHTML(globalEditor);
});
<!-- https://cdn.ckeditor.com/#ckeditor5 -->
<script src="https://cdn.ckeditor.com/ckeditor5/23.1.0/classic/ckeditor.js"></script>
<div id="editor">
<h1>This is a heading</h1>
<p>This is some sample content.</p>
</div>
<p>
<button class="btn">Get Selected HTML</button>
</p>
<textarea class="selected" rows="8" cols="72"></textarea>
Upvotes: 1