I can use the following code to get selected text:
text=window.getSelection(); /// for Firefox text=document.selection.createRange().text; /// for IE
But how can I get the selected Html, which includes the text and html tags?
It works by using the document. execCommand('copy'); function. With this function you'll copy the select text. This will not only work with textarea s but with every selected text on the webpage (like in span , p , div , etc.).
Definition and UsageThe selected attribute is a boolean attribute. When present, it specifies that an option should be pre-selected when the page loads. The pre-selected option will be displayed first in the drop-down list. Tip: The selected attribute can also be set after the page loads, with a JavaScript.
You can use the user-select property to disable text selection of an element. In web browsers, if you double-click on some text it will be selected/highlighted. This property can be used to prevent this.
Here's a function that will get you HTML corresponding to the current selection in all major browsers. It also handles multiple ranges within a selection (currently only implemented in Firefox):
function getSelectionHtml() { var html = ""; if (typeof window.getSelection != "undefined") { var sel = window.getSelection(); if (sel.rangeCount) { var container = document.createElement("div"); for (var i = 0, len = sel.rangeCount; i < len; ++i) { container.appendChild(sel.getRangeAt(i).cloneContents()); } html = container.innerHTML; } } else if (typeof document.selection != "undefined") { if (document.selection.type == "Text") { html = document.selection.createRange().htmlText; } } return html; } alert(getSelectionHtml());
In IE <= 10 browsers, it's:
document.selection.createRange().htmlText
As @DarrenMB pointed out IE11 no longer supports this. See this answer for reference.
In non-IE browsers, I just tried playing with this... this seems to work, WILL have side effects from breaking nodes in half and creating an extra span, but it's a starting point:
var range = window.getSelection().getRangeAt(0), content = range.extractContents(), span = document.createElement('SPAN'); span.appendChild(content); var htmlContent = span.innerHTML; range.insertNode(span); alert(htmlContent);
Unfortunately, I can't seem to put the node back as it was (since you can be pulling half the text from a span, for instance).
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