Find the deepest element containing every given node
A comment widget lets readers highlight several words scattered across an article. To anchor the comment, the widget needs the innermost element that wraps every highlighted node. Wrapping or scrolling to that element brings the whole selection along with it.
Implement commonContainer(nodes, selector). It returns the deepest element that contains every node in nodes.
commonContainer(nodes, selector?) // => Element | null
nodes is an array of Element and Text nodes. It may contain duplicates, in any order.Element, never a text node. A text node is contained by its parent element.selector is given (a CSS selector string), return the deepest common container that matches the selector instead. The answer may be the plain common container itself, or one of its ancestors.null when:
nodes is empty.selector.<article id="post">
<section id="intro">
<p id="p1">Hello <em id="em">brave</em> world</p>
<p id="p2">Second line</p>
</section>
<section id="body"><p id="p3">Third</p></section>
</article>
commonContainer([p1, p2]); // => section#intro
commonContainer([em, p1]); // => p#p1 (p1 contains em)
commonContainer([em.firstChild]); // => em#em (text node "brave")
commonContainer([p1.firstChild, em]); // => p#p1
commonContainer([p2, p3]); // => article#post
commonContainer([p1, p2], 'article'); // => article#post
commonContainer([em], 'section'); // => section#intro
commonContainer([em], 'table'); // => null
commonContainer([]); // => null
commonContainer([p1, document.createElement('div')]); // => null
document.createRange, commonAncestorContainer).