The content management system I wrote for our site uses a bookmarklet to post articles, which reads the selected area on a page with document.getSelection(). But in some cases it would be very useful to read the underlying HTML code for the selected area as well, to get links and other HTML formatting.
Anyone know of a jQuery plugin or other Javascript technique to access the raw HTML that produces a selected area?
First, as you said, get the selection
This does have some details about selected nodes, too, but if you want to do more then convert this to a range (If
.rangeCount > 1you may want to loop here)Next, using
range.commonAncestorContainerandrange.startContainerwalk through the DOM tree performing whatever you want until you reachrange.endContainer.All of these nodes should be in the selection.
Here is some code that’ll return all (top level) selected nodes and, optionally, apply a callback to every node in selection.