views:

683

answers:

1

Hello,

I'm developing a Firefox extension, where the user selects a text, then that text goes to a REST webservice and brings some results back.

My problem with text selection, I've used this method to get the selected text:

var selectedText = window.getSelection();

I got the result in selectedText variable and send it to the server, but I don't know how to get this node's Id or anything to append the result into it.

I tried it in both javascript and jQuery with Firebug and a lot of Google search queries, but no useful result!

+2  A: 

Edit: Since you need this for a FF extension you can skip all the functions for IE and everything you need to do is this:

window.getSelection().getRangeAt(0).commonAncestorContainer

More information about Ranges: https://developer.mozilla.org/en/DOM/range


There already is a similar question:

Get selected text and selected nodes on a page?

I modified the functions a bit:

<script type="text/javascript">
  function getTextSelection() {
    if(document.selection)
      return document.selection;
    else if(window.getSelection)
      return window.getSelection();
    else if(document.getSelection)
      return document.getSelection();
    else
      return false;
  }
  function getSelectionRange() {
    var selection = getTextSelection();
    if(selection.getRangeAt)
      return selection.getRangeAt(0);
    else if (selection.createRange)
      return selection.createRange();
    else
      return false;
  }
  function getSelectionParent(r) {
    if(r.parentElement)
      return r.parentElement;
    else if(r.commonAncestorContainer)
      return r.commonAncestorContainer;
    else
      return false;
  }
</script>

HTML:

<body>
  <p><em>This is just some random text. </em><strong>Select me and then click the button!!!</strong></p>
  <p><input type="button" value="Parent element?" onclick="alert('The selection\'s parent element is: ' + getSelectionParent(getSelectionRange()).nodeName);" /></p>
</body>

I tested this stuff in IE6,7 and FF3.0. Worked without any problems. The only thing you must be aware of is that IE unlike FF ignores text nodes.

If you want to try it out yourself: http://dev.freedig.org/files/selection.html

slosd
I read it, it just gives you the selected text not the node, am I wrong?
Khaled Al Hourani
The last code example gets the parent node of the text selection. I added it to my answer.
slosd
thanks but it doesn't work either :( even in the demo link it doesn't give you the object or the element
Khaled Al Hourani
What browser are you using? I tried it with IE and FF and it worked. getSelectionParent(getSelectionRange()) returns an element-node.
slosd