11

When selecting texts in HTML documents, one can start from within one DOM element to another element, possibly passing over several other elements on the way. Using DOM API, it is possible to get the range of the selection, the selected texts, and even the parent element of all those selected DOM elements (using commonAncestorContainer or parentElement() based on the used browser). However, there is no way I am aware of that can list all those containing elements of the selected texts other than getting the single parent element that contains them all. Using the parent and traversing the children nodes won't do it, as there might be other siblings which are not selected inside this parent.

So, is there is a way that I can get all these elements that contains the selected texts. I am mainly interested in getting the block elements (p, h1, h2, h3, ...etc) but I believe if there is a way to get all the elements, then I can go through them and filter them to get what I want. I welcome any ideas and suggestions.

Thank you.

cria
  • 205
  • 1
  • 5
  • 12

4 Answers4

23

Key is window.getSelection().getRangeAt(0) https://developer.mozilla.org/en/DOM/range

Here's some sample code that you can play with to do what you want. Mentioning what you really want this for in question will help people provide better answers.

var selection = window.getSelection();
var range = selection.getRangeAt(0);
var allWithinRangeParent = range.commonAncestorContainer.getElementsByTagName("*");

var allSelected = [];
for (var i=0, el; el = allWithinRangeParent[i]; i++) {
  // The second parameter says to include the element 
  // even if it's not fully selected
  if (selection.containsNode(el, true) ) {
    allSelected.push(el);
  }
}


console.log('All selected =', allSelected);

This is not the most efficient way, you could traverse the DOM yourself using the Range's startContainer/endContainer, along with nextSibling/previousSibling and childNodes.

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
  • Not the perfect solution as you said, but it gave me an idea on how to do it. Therefore, I chose this as the most correct answer to my need. Really appreciate this. – cria Nov 19 '10 at 12:45
  • This is a decent answer, but will not work in IE < 9. It could do with a check that the selection exists before calling `selection.getRangeAt(0);` too (using the selection's `rangeCount` property is easiest). – Tim Down Nov 19 '10 at 12:53
  • There are lots of gotchas that I did not address, this is just to start heading in the right direction. Your library requires 22k of uncompressed javascript to really handle it and if I needed it, I would just use that. – Ruan Mendes Nov 19 '10 at 18:32
  • 2
    @TimDown It also doesn't work on IE11, so this has 0 IE support. – realappie Apr 13 '17 at 08:03
  • @Abdel: I suspect it will work in IE 11 with the addition of `selection.removeAllRanges(); selection.addRange(range);`. – Tim Down Apr 13 '17 at 12:06
  • 2
    @TimDown `selection.containsNode` doesn't work on IE 11, don't suspect. [Test](http://prntscr.com/evyana). – realappie Apr 13 '17 at 12:23
11

You can use my Rangy library to do this. It provides an implementation of DOM Range and Selection objects for all browsers, including IE, and has extra Range methods. One of these is getNodes():

function isBlockElement(el) {
    // You may want to add a more complete list of block level element
    // names on the next line
    return /h[1-6]|div|p/i.test(el.tagName);
}

var sel = rangy.getSelection();
if (sel.rangeCount) {
    var range = sel.getRangeAt(0);
    var blockElements = range.getNodes([1], isBlockElement);
    console.log(blockElements);
}
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • 1
    I have no doubt that this code is the most accurate one. But using your lib is an overkill for my case due to the large size of the lib. Therefore, I chose the other answer even though it has some issues that I need to handle. If there was a choice to pick two answers, I would surely mark yours as well. Keep up the great lib/work :) – cria Nov 19 '10 at 12:43
  • @cria: Fair enough. What you get with mine is support for IE. – Tim Down Nov 19 '10 at 12:54
  • 3
    @TimDown thank you for your work on Rangy. It makes a set of complicated problems much much easier. – Joshua Enfield Jan 24 '14 at 22:06
  • Maybe I'm just stupid, but looking at the README I have no idea exactly how to use this library. I suppose I need to add a script tag referencing a `.js` file *somewhere* but where? I looked in the `lib` directory, but there are 6 different files, none of which appears to be a top-level file. Having to start looking at actual source to figure this out is going to make me grumpy, and I haven't even gotten to the part of exactly how to use it were I to figure out how to make it available to my js code. (the example is nice but the getNodes link is broken so I have no idea what other functionali – Michael Nov 20 '22 at 03:57
  • 1
    @Michael: That's fair. When it was developed, there were far fewer standards about how to package JS libraries, but even then, I don't think I made great choices on that front, and the README could do with explicit instructions, which I shall add. Anyway: you need to include `lib/rangy-core.js` in a ` – Tim Down Nov 21 '22 at 10:14
  • @Michael: Also, I thought I'd extracted `getNodes()` from Rangy and posted it as an answer at some point but it seems not. There is a non-Rangy equivalent of `getNodes()` here: https://stackoverflow.com/questions/667951/how-to-get-nodes-lying-inside-a-range-with-javascript/7931003#7931003 – Tim Down Nov 21 '22 at 10:20
  • Thanks! I poked around for a while and did find the documentation in the readme; I see you've changed the link in the answer to match. – Michael Nov 21 '22 at 17:44
1

It sounds like you could use Traversing from the jQuery API.

Possibly .contents()

Hope that helps!

jasonflaherty
  • 1,924
  • 7
  • 40
  • 82
  • 1
    Yeah the methods there are all great. But I don't believe I can use the browser selected text range as an input for those methods, can I? or maybe I am missing something... Thanks – cria Nov 18 '10 at 23:12
1

Here is a es6 approach based on @Juan Mendes response:

const selection = window.getSelection();
const range = selection.getRangeAt(0);
const elementsFromAncestorSelections = range.commonAncestorContainer.getElementsByTagName("*");

const allSelectedElements = Array.from(elementsFromAncestorSelections).reduce(
  (elements, element) =>
    selection.containsNode(element, true)
      ? [...elements, element]
      : elements,
  [],
);
  • Thank you, I never would have stumbled on 'reduce' without this. And if i had, i probably wouldn't have realized its usefulness. – captain puget Feb 26 '21 at 22:20
  • Is there a simple way to only take the top-most complete nodes? i don't want intermediate nodes for which not all children are in the selection, nor children for which the reverse is true (where i do want the intermediate nodes for which all children are in the selection; i don't want any of the children in this case) – Michael Nov 20 '22 at 03:51
  • Your reduce really should have been a `filter` and you wouldn't need to create a new array for every iteration. – Ruan Mendes Jan 05 '23 at 15:35