glarkou
glarkou

Reputation: 7101

Get first div containing the selection

I use getSelection() (javascript) to get a string onmouseup.

Is it possible to get the div containing the selection? or the parent element containing the selection if it is not a div?

The code is similar to this JSFiddle Example and I want to be able to identify if the selection was inside first div or second div.

Thanks

Upvotes: 0

Views: 133

Answers (2)

ben author
ben author

Reputation: 2955

Your selection object contains a range.

var my_selection = window.getSelection();
var my_range  = my_selection.getRangeAt(0);

Sounds like you want commonAncestorContainer, which is most specific element that contains both your start and end elements.

Some other useful methods on the range... startContainer and startOffest will get you the element and position in the element where the range begins. Similarly, endContainer and endOffset.

Upvotes: 1

Chibuzo
Chibuzo

Reputation: 6117

I don't understand your question so well, but however try this

var parent_div = $("your-selection").parent();

The code will get the element containing the selection, although I don't know what your selection is.

Upvotes: 0

Related Questions