Question

I was testing out the getSelection() method, and I wanted my program to get the selected text in a certain paragraph of text and display it in a div tag. I used the following code:

var txt = document.getSelection();
document.getElementById("display").innerHTML = "The text you have selected is: " + txt + ".";

However, I want the program to only get selections made in the paragraph itself, not in the entire document. I tried using document.getElementById("id").getSelection(); but it didn't work.

How can I make it so getSelection() only applies to a certain element?

Was it helpful?

Solution

Here's one approach, tested only in Chromium 19 (Which supports textContent, for Internet Explorer innerText would have to be used instead):

function getSelectedText() {
    if (window.getSelection) {
        return window.getSelection().toString();
    } else if (document.selection) {
        return document.selection.createRange().text;
    }
    return '';
}

var b = document.getElementsByTagName('body')[0],
    o = document.getElementById('output');

b.onmouseup = function(e){
    var selText = getSelectedText(),
        targetElem = e.target.tagName.toLowerCase();
    if (selText && targetElem == 'p') {
        o.textContent = 'You selected the text: "' + selText + '" from a ' + targetElem + ' element.';
    }
};​

JS Fiddle demo.

OTHER TIPS

getSelection() is only available as a method of window and document. If you want to get a Range representing just the portion of the user selection that lies within a particular node, here's a function to do that, using my Rangy library (the code to do without the library would be longer and is beyond my enthusiasm to write right now):

function getSelectedRangeWithin(el) {
    var selectedRange = null;
    var sel = rangy.getSelection();
    var elRange = rangy.createRange();
    elRange.selectNodeContents(el);
    if (sel.rangeCount) {
        selectedRange = sel.getRangeAt(0).intersection(elRange);
    }
    elRange.detach();
    return selectedRange;
}
function getSelected() {
    if(window.getSelection) { return window.getSelection(); }
        else if(document.getSelection) { return document.getSelection(); }
                    else {
                            var selection = document.selection && document.selection.createRange();
                            if(selection.text) { return selection.text; }
                return false;
            }
            return false;
        }

written in coffeescript:

getSelected = ->
  if window.getSelection
    return window.getSelection()
  else if document.getSelection
    return document.getSelection()
  else
    selection = document.selection and document.selection.createRange()
    return selection.text  if selection.text
    return false
  false

delicious javascript

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top