Get the selected HTML from an FCKEditor instance
Posted April 17th, 2009 in FCKEditor
In the last FCKEditor post I wrote how to get the selected text from an FCKEditor instance and in this post will look at how to do the same but to return the HTML source of the selection which will include all the tags etc.
Getting the HTML as plain text
The following function is based on some code from
http://www.fckeditor.net/forums/viewtopic.php?f=6&t=11997&p=31833
Note that the implementation returns HTML including any of the special FCKEditor placeholders etc in the code and may not be suitable for working with. I'll show the function first and then some example output from a selection.
The parameter "instance_name" is the name of the FCKeditor instance.
function get_selection_html(instance_name) {
var oFCKeditor = FCKeditorAPI.GetInstance(instance_name);
var selection = (oFCKeditor.EditorWindow.getSelection ? oFCKeditor.EditorWindow.getSelection() : oFCKeditor.EditorDocument.selection);
if(selection.createRange) {
var range = selection.createRange();
var html = range.htmlText;
}
else {
var range = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
var clonedSelection = range.cloneContents();
var div = document.createElement('div');
div.appendChild(clonedSelection);
var html = div.innerHTML;
}
return html;
}
The createRange test is needed to make sure the code works in both Internet Explorer and in other browsers. IE uses the selection.createRange() part and other browsers use the other part.
If the current selection in the FCKEditor contained the following HTML:
<p>This is line 1</p> <p>This is <a href="http://www.example.com">line</a> 2<br /> This a line break in line 2</p> <p>This is line 3</p>
In Firefox, Safari (tested on Windows only) and Chrome the value returned should be this:
<p>This is line 1</p> <p>This is <a href="http://www.example.com" _fcksavedurl="http://www.example.com">line</a> 2<br> This a line break in line 2</p> <p>This is line 3</p>
In Internet Explorer and Opera it will return this:
<P>This is line 1</P> <P>This is <A href="http://www.example.com" _fcksavedurl="http://www.example.com">line</A> 2<BR>This a line break in line 2</P> <P>This is line 3</P>
Note that the only real difference between the first and second above is that the tags are in uppercase. Also note the HTML is not XHTML compliant. Again, as noted earlier, please use this function with caution and the values returned are not exactly as is seen when viewing the HTML source.
Related posts:
- Get the selected text from an FCKEditor instance (Tuesday, April 7th 2009)
- Get the HTML from an FCKEditor instance (Sunday, March 29th 2009)
- Getting a handle to an FCKEditor Editor Instance (Tuesday, March 17th 2009)
- Insert HTML into FCKEditor (Friday, February 13th 2009)
- Always make FCKEditor paste as plain text (Tuesday, November 11th 2008)
- Using the FCKEditor HTML Editor with PHP (Wednesday, August 20th 2008)

Comments
blog comments powered by Disqus