Determine HTML Node name given a javascript selection object
How can I determine the node (what tag this innerHTML is associated with) that is associated with a given ja开发者_StackOverflow社区vascript selection object? I am using window.getSelection() and would like to know in which div/span class the selection is in.
Thank you!
If you want the deepest element that contains the whole of the selection, the easiest way is to obtain a Range
object from the selection and use its commonAncestorContainer
property.
jsFiddle: http://jsfiddle.net/5LvEG/1/
Code:
function getSelectionContainerElementId() {
var sel = window.getSelection();
if (sel.rangeCount > 0) {
var range = sel.getRangeAt(0);
var container = range.commonAncestorContainer;
// container could be a text node, so use its parent if so
if (container.nodeType == 3) {
container = container.parentNode;
}
return container.id;
}
return null;
}
alert(getSelectionContainerElementId());
精彩评论