Monday, May 20, 2024
95
rated 0 times [  102] [ 7]  / answers: 1 / hits: 75170  / 13 Years ago, wed, april 13, 2011, 12:00:00

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?


More From » getselection

 Answers
7

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).


[#92769] Monday, April 11, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ariel

Total Points: 523
Total Questions: 111
Total Answers: 100

Location: Anguilla
Member since Sun, Jan 29, 2023
1 Year ago
;