I'm working on a custom generator of link in CKEditor. What I would like to do is getting the html that has been selectioned by the user. I tried a lot of thing, my last function is that
function getTheHtml(editor) {
var selection = editor.getSelection();
if (selection.getType() == CKEDITOR.SELECTION_ELEMENT) {
var selectedContent = selection.getSelectedElement().$.outerHTML;
} else if (selection.getType() == CKEDITOR.SELECTION_TEXT) {
if (CKEDITOR.env.ie) {
selection.unlock(true);
selectedContent = selection.getNative().createRange().text;
} else {
selectedContent = selection.getNative();
}
}
return selectedContent;
}
this works pretty well but I still have issue, if the user select text it works, if he select an image it works but when the user select an image plus some text i only get the text for exemple this is what the user really select
<img align="" alt="" border="0" class="donotlink" hspace="5" src="image/pic.jpg" vspace="5" />Some Random Text
and this is what i get from my function
Some Random Text
I also tried to do this:
function getSelectionHtml(editor) {
var sel = editor.getSelection();
var ranges = sel.getRanges();
var el = new CKEDITOR.dom.element("div");
for (var i = 0, len = ranges.length; i < len; ++i) {
el.append(ranges[i].cloneContents());
}
return el.getHtml();
}
but then it select the first closest node and when I try to wrap the selection with the "a" tag it I can't wrap what the user selected in the first place
I know this has been a frequent topic but since I didn't found how to fix... Thanks in advance.
Use range.cloneContents(). With anything selected in your editor, call the following code in the console:
var editor = CKEDITOR.instances.editor1,
range = editor.getSelection().getRanges()[ 0 ],
el = editor.document.createElement( 'div' );
el.append( range.cloneContents() );
console.log( el.getHtml() );
It is working for both image and text.
var selection = CKEDITOR.instances.getSelection();
if (selection.getType() == CKEDITOR.SELECTION_ELEMENT) {
var selectedContent = selection.getSelectedElement().$.outerHTML;
} else if (selection.getType() == CKEDITOR.SELECTION_TEXT) {
if (CKEDITOR.env.ie) {
selection.unlock(true);
selectedContent = selection.getNative().createRange().text;
} else {
selectedContent = selection.getNative();
console.log("The selectedContent is: " + selectedContent);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With