Reputation: 354
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
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;
}
};
(Select some text before 5 Seconds then look in the console)
Upvotes: 2
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
Upvotes: 2