Chrome not getting selected html line wrapping tags (contenteditable)
I use this Tim Down solution to get the selected html in a contenteditable div and it works great (thanks Tim!) But using Chrome if I select the html string exactly within the bounds of the html tag like in this image: http: // i. imgur.com/UiYzrcp.png 1 :
which i get as plain text ( test
in this case).
If I expand the selection to the next character (like a letter c
), I get the correct html ( <strong>test</strong> c
) instead .
Can I get the complete html in Webkit by selecting a word like the image? Thanks to
source to share
Not really. WebKit normalizes every border of any range when added to a selection to conform to WebKit's idea of correct selection / caret positions in the document. You can modify the original function so that it detects a selection case that contains all the text within an element and expands the selection range to surround that element (without actually changing the selection). Here's a simple example (you might want something smarter for a more general case, like when text is inside nested elements, detects block / inline elements, etc.):
Demo: http://jsfiddle.net/btLeg/
code:
function adjustRange(range) {
range = range.cloneRange();
// Expand range to encompass complete element if element text
// is completely selected by the range
var container = range.commonAncestorContainer;
var parentElement = container.nodeType == 3 ?
container.parentNode : container;
if (parentElement.textContent == range.toString()) {
range.selectNode(parentElement);
}
return range;
}
function getSelectionHtml() {
var html = "", sel, range;
if (typeof window.getSelection != "undefined") {
sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
range = adjustRange( sel.getRangeAt(i) );
container.appendChild(range.cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
return html;
}
source to share