2

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"- http://code.google.com/p/rangy/ for this purpose? Or can this be achieved using pure js or jquery code?

Pavlo
  • 43,301
  • 14
  • 77
  • 113
Arvind
  • 6,404
  • 20
  • 94
  • 143
  • Have a look at [this](http://stackoverflow.com/questions/5222814/window-getselection-return-html). This might help. – albertjan Jul 25 '12 at 07:37

2 Answers2

3

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();
}
Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
0

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.

codef0rmer
  • 10,284
  • 9
  • 53
  • 76
  • if the selection is within some top level html nodes, then will I also get the top level nodes with the selection's HTML, in the demo you have provided? Basically, I need the entire node path, from top level node downwards, for the current selection... Also will the demo work with selections that include images/links/tables? Thanks... – Arvind Jul 25 '12 at 08:45