5

Can I query (in a jQuery sense) the DOM elements - not just text nodes - completely selected by the mouse?

Randomblue
  • 112,777
  • 145
  • 353
  • 547

2 Answers2

2

This will get you all the elements that are completely selected:

var currentSelection = window.getSelection();
var firstRangeInSelection = currentSelection.getRangeAt(0);
var commonAncestor = firstRangeInSelection.commonAncestorContainer;

var nodesInSelection = $(commonAncestor).find("*").filter(function() {
                           return currentSelection.containsNode(this, false);
                       });

For more info on DOM Selections, check out this page.

Red Orca
  • 4,755
  • 1
  • 15
  • 12
  • +1, although it would be improved by a few checks: first, IE < 9 does not support `window.getSelection()` so you should check for the existence of that; second, `getRangeAt(0)` will throw an error if nothing is selected, so you should check the `currentSelection.rangeCount` is greater than zero. – Tim Down Oct 23 '11 at 20:01
  • Actually, what happens if the selection is completely contained within a single text node? I presume you'll get an empty jQuery object. – Tim Down Oct 23 '11 at 20:03
1

You could adapt my answer to the following question to return you a jQuery object rather than an array, which should be simple:

JS: Get array of all selected nodes in contentEditable div

However, this won't work in IE < 9, which does not support the same Selection object as other browsers. For that, you'll need another approach. There is my own Rangy library, as mentioned in that answer, but if you need IE < 9 support without a library then I can knock something together.

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • @Chris: I wasn't referring to your answer. I had assumed the OP would want a jQuery collection rather than an array, which is what the answer of mine I linked to produces. – Tim Down Oct 23 '11 at 19:58