If you are using window.getSelection()
, it returns a selection object which contains properties .anchorNode
and .focusNode
which are the nodes at the start and end of the selection. You can then use those nodes to walk up the parent chain to find any level of parent you want.
The closest common parent could be found by getting the immediate parent of the first object and then seeing if it is also a parent of the second object. If not, go up one parent higher until you eventually find a common parent.
function findCommonParentElement(startNode, endNode) {
// see if node has a particular parent
// by walking up the parent chain and comparing parents
function hasParent(node, parent) {
while (node && node !== parent && node !== document.body) {
node = node.parentNode;
}
return node === parent;
}
// for text nodes, get the containing element
// for elements, just return what was passed in
function getElement(node) {
while (node && node.nodeType !== 1) {
node = node.parentNode;
}
return node;
}
// go up the parent chain of endNode looking for a node
// that startNode has as a parent
while (endNode && !hasParent(startNode, endNode)) {
endNode = endNode.parentNode;
}
// return the containing element - so it won't return a textnode
return getElement(endNode);
}
// Usage:
var sel = window.getSelection();
var commonParent = findCommonParentElement(sel.anchorNode, sel.focusNode);
Working demo: http://jsfiddle.net/jfriend00/GV96w/