How to obtain range object for window.getSelection()?

In a js function, I want to obtain all Nodes(HTML elements) that are part of the content in a web page, when the content has been selected by the user.

Now, I understand that window.getSelection() will give me a selection object. Also, this selection object has to be converted into a range object, before I can obtain the list of nodes(HTML elements) that are part of that selection.

How do I obtain the range object? From what i read, different browsers have different implementations of range objects...Initially, I will use this js function only in Google Chrome...So code should work perfectly in Google Chrome... but I do want that the code works across all/most new versions of Google Chrome... The code may be JS or pure Jquery.

One more question-- do I have to use a js library like "Rangy"- for this purpose? Or can this be achieved using pure js or jquery code?


Apart from IE < 9, all major browsers implement the same standards for Selection and Range and have done for years. There are some differences but the APIs are the same. If you're not bothered about IE < 9 then you really don't need to use Rangy (it's around 40KB before gzipping), although it does have a convenient method for getting nodes that you may find helpful.

To get the nodes within the selection, you can get the selected range like this:

var sel = window.getSelection();
if (sel.rangeCount > 0) {
    var range = sel.getRangeAt(0);

To get the nodes from the range, you could use the code from this answer. If you used Rangy, it would be

var sel = rangy.getSelection();
if (sel.rangeCount > 0) {
    var range = sel.getRangeAt(0);
    var nodes = range.getNodes();

I can see the problem that you are facing is not to get a range object but to find the HTML nodes inside the selection. In this demo, if you select text and click 'get selection html' button, you get the selected text including the DOM. Once you get that, you can find a list of DOM nodes using jquery code. Let me know if you need more info on this.

Need Your Help

git rm --cached not working

git github

I have been trying to remove some files from the git version control system so that they are not pushed on commits.