By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,967 Members | 1,236 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,967 IT Pros & Developers. It's quick & easy.

Javascript Selection Issue

P: 1

I am facing the difficulty in the selecting a text on the browser . And highlighting the text.
I am using the window.getSelection() to get the object and after that i am using the range.getRangeAt(0).cloneContents() method for getting the copy of the document content my requirement is to get the exact html text . But when we are assigning the text into the innerHTML it complete the DOm structure i m not getting the exact HTML text of the document . For example :- if user select the text <i>"why"</i></b> now i m getting the html text as <b><i>"why"</i></b> after applying the below code code. This is the code that i m using :-

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>The serialized HTML of a selection in Mozilla and IE</title>
<script type="text/javascript">
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');
return div.innerHTML;
else {
return '';
else {
return '';
<p>Some text to test the selection on.
Kibology for <b>all</b>. All <i>for</i> Kibology.
<form action="">
<input type="button" value="show HTML of selection"
onclick="this.form.output.value = getHTMLOfSelection();">
<textarea name="output" rows="5" cols="80"></textarea>

Assist me to get rid from this problem.....

Sep 24 '08 #1
Share this Question
Share on Google+
2 Replies

Expert 100+
P: 392
Try setting it to the .innerText attribute vs the .innerHTML attribute.
Sep 24 '08 #2

Expert 100+
P: 392
Ahhh.... I think I might be seeing the problem. You are using the DOM API's with what is probably a String object being returned from getRangeAt(). The DOM API's are esceaping the tags included in the String object.

So instead of this
Expand|Select|Wrap|Line Numbers
  1. var clonedSelection = range.cloneContents(); 
  2. var div = document.createElement('div'); 
  3. div.appendChild(clonedSelection); 
  4. return div.innerHTML;
Try this
Expand|Select|Wrap|Line Numbers
  1. var clonedSelection = range.cloneContents(); 
  2. return clonedSelection.toString();

P.S. Please use code tags when pasting code.
Sep 24 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.