I have a Javascript routine that retrieves the selection text by a user formatted as HTML:
function getHTMLOfSelection() {
var range;
if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
return range.htmlText;
}
else if (window.getSelection) {
var selection = window.getSelection();
if (selection.rangeCount > 0) {
range = selection.getRangeAt(0);
var clonedSelection = range.cloneContents();
var div = document.createElement('div');
div.appendChild(clonedSelection);
return div.innerHTML;
}
else {
return '';
}
}
else {
return '';
}
}
With the fiddle, make sure and select the quoted text first:
http://jsfiddle.net/userdude/Y4BBq/13/
The code works fine, however, the selection includes a \r\n after every </p> and <br/>.
Why are these added and at what point? It seems redundant, as the <p> and <br> tags already include the new line.
As per OP’s comment, if you want to return the HTML without line breaks, you can just use a regex to globally replace the
Carriage Return(\n) andLine Feed(\r) characters by empty strings:This will remove all line breaks, beware that the HTML will lose readability if you select a long part of document.
JSFiddle