views:

305

answers:

2

Hello,

I have the following function that is supposed to get HTMLs for the user selected area on the web page. This function does not seems to work properly.

Sometime, it gets htmls which is not selected also.

Can anyone please look into this function? -- Thanks a lot.

//----------------------------Get Selected HTML------------------------

function getSelectionHTML(){

if (window.getSelection)
{
 var focusedWindow = document.commandDispatcher.focusedWindow;
 var sel = focusedWindow.getSelection();
 var html = "";
 var r = sel.getRangeAt(0);
 var parent_element = r.commonAncestorContainer;   
 var prev_html = parent_element.innerHTML;
 if(prev_html != undefined)
 {
  return prev_html; 
 }
 return sel;
}
return null;

}

+1  A: 

It looks to me like you're getting the contents of the parent element rather than the selection itself. If the parent element contains anything other than what you have selected, then you'll get that too.

var sel = focusedWindow.getSelection();

This line returns a selection object. It contains the exact text selected by the user. You then get the range from the selection and get the commonAncestorContainer. So if you have code like this:

<div id="ancestor">
    <p>First sentence.</p>
    <p>Another sentence.</p>
</div>

And your user selects from the 's' of the first sentence to the 's' of the second sentence then the commonAncestorContainer is the div element so you'll also get the rest of the text.

A good reason for this would be if you wanted to guarantee yourself a valid HTML fragment (this seems to be the case, implied by your function name), but if you just want the selected text then call the toString method on the range directly:

var focusedWindow = document.commandDispatcher.focusedWindow;
var sel = focusedWindow.getSelection();
var r = sel.getRangeAt(0);
return r.toString();
robertc
A: 

Thanks you kind sir

Murali Bala