2

How can i get the id of the container (say, id of the p or div) of a user selected text?

I want to make list of selected texts, user selects a text then clicks on a button to add to the list. And when user clicks the text from the list i want to highlight the place where original selection was made. I need the id of the container because the selected text may not be unique and appear multiple times in the document.

i get the selected text like this Return HTML from a user-selected text

Community
  • 1
  • 1
Desu
  • 344
  • 1
  • 9

2 Answers2

2

window.getSelection().anchorNode - Gives you the DOM element where the selection started window.getSelection().focusNode - Gives you the DOM element where the selection ended

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Selection?redirectlocale=en-US&redirectslug=DOM%2FSelection

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • 1
    in Chrome(i assume all WebKit based browsers too): anchorNode gives all of the text in the container where the selection is started. focusNode gives all of the text in the container where the selection is ended. – Desu Jul 14 '13 at 19:47
  • And how can I get the array of the dom elements which the text was selected? anchorNode and focusNode just returns the first and the last one. What about the middle ones? – Flezcano Jul 17 '17 at 15:10
2

Here is one way it can be achieved cross browser (untested)

var getSelectionContainer = function() { 

    if (document.selection){  // IE
        return document.selection.createRange().parentElement();
    }

    var select = window.getSelection();
    if (select.rangeCount > 0) {
       return select.getRangeAt(0).startContainer.parentNode;
    }
};

Demo

(Select some text before 5 Seconds then look in the console)

Links

MDN window.getSelection

MDN selection.getRangeAt

MDN range.startContainer

MDN selection.rangeCount

iConnor
  • 19,997
  • 14
  • 62
  • 97