Desu
Desu

Reputation: 354

javascript / jQuery : get selected text's container

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

Upvotes: 3

Views: 2195

Answers (2)

iConnor
iConnor

Reputation: 20189

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

Upvotes: 2

CodingIntrigue
CodingIntrigue

Reputation: 78525

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

Upvotes: 2

Related Questions