Can I query (in a jQuery sense) the DOM elements - not just text nodes - completely selected by the mouse?
Asked
Active
Viewed 127 times
5
-
What does "highlight" mean exactly? And, even more so, what does "partially highlight" mean? – Jon Oct 23 '11 at 17:36
-
Take a look at this: http://stackoverflow.com/questions/7803016/how-to-wrap-html-tag-for-jquery-mouseup-selection-wrods/7803559#7803559 – Frederick Behrends Oct 23 '11 at 17:45
-
1@Randomblue "selected" is the more familiar term for that... – Šime Vidas Oct 23 '11 at 17:46
-
@Randomblue Consider `:selection` – Šime Vidas Oct 23 '11 at 17:57
-
@ŠimeVidas: Good idea! I'll edit the question. – Randomblue Oct 23 '11 at 17:59
-
Have a look at the [`window.getSelection`](https://developer.mozilla.org/en/DOM/window.getSelection) method. I'm heading off, so I cannot post the full answer. – Rob W Oct 23 '11 at 18:09
2 Answers
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.
-
@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