简体   繁体   中英

javascript-how to use pure JS/jquery/rangy/other lib to obtain the highest level node in web page, whose entire text matter has been selected by user

Given below is an example HTML page snippet---

<div id="maindiv">
    <div id="div1">
      Text 1 
      <div id="div1_1"> Text 1_1 </div>
      <div id="div1_1"> <a href="http://google.com/">Text 1_2</a> </div> 
    </div>
    <div id="div2"> Text 2  </div>
</div>

Now there are a couple of scenarios here, the web page containing text above is displayed in browser, and user selects some of the text displayed in browser--

Scenario 1--

User selects text

Text 1_1  

in web page

Scenario 2--

User selects text

Text 1  Text 1_1  Text 1_2 

in web page.

Scenario 3-- User selects following text Text 1 Text 1_1 Text 1_2 Text 2

Scenario 4-- User selects following text

Text 1_2 Text 2

Now I want to obtain using Javascript, the topmost node, whose entire content has been selected by the user. This is a single div in scenario 1 viz. "div1_1", scenario 2 viz. "div1" and scenario 3 viz. "maindiv", but in scenario 4, entire content of div1_2 as well as entire content of div2 are selected-- ie these 2 divs whose content has been selected, are not siblings. So the result I want to extract for scenario 4 is "div1_2" and "div2".

How do I extract the div as mentioned above? I have mentioned use of rangy here because its pretty useful and has some feature over and above standard JS DOM, but I am open to using any other JS library like JQuery, or even pure Javascript.

One more thing that i want to add/ask here... even if there are more images, more links in any of the divs, and the user's selection includes those images/links, then how will I extract the uppermost div, such that this div's text content equals the text selected by user (images can be ignored and link's texts only have been selected by the user along with regular text)?

Sounds to me as though you want the commonAncestorContainer property of the selection range. Note that it could be a text node or an element. I'm using Rangy below for IE < 9 compatibility but if you don't need that then you could just use window.getSelection() instead of rangy.getSelection() .

var sel = rangy.getSelection();
var selContainerNode = null;
if (sel.rangeCount > 0) {
    selContainerNode = sel.getRangeAt(0).commonAncestorContainer;
}

If you want the innermost element (rather than potentially a text node) that contains the selection, do a simple check of commonAncestorContainer 's node type:

if (selContainerNode.nodeType == 3) {
    selContainerNode = selContainerNode.parentNode;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM