I've looked around for a while, but there doesn't seem to be a simple way to do this. jQuery doesn't help the in least, it seems to entirely lack any support for selection or DOM ranges. Something which I hoped would be as simple as $.selection.filter('img')
seems to only be doable with dozens of lines of code dealing with manually enumerating elements in ranges and browser implementation inconsistencies (though ierange helps here). Any other shortcuts?
views:
105answers:
3
+1
A:
var fragment = getSelection().getRangeAt(0).extractContents();
The nodes in the selection will be removed and returned in a DocumentFragment
, and you can now access the childNodes
of fragment
just like you would any element.
Delan Azabani
2010-05-08 09:40:53
A few points: first, you've missed off the parentheses from `cloneContents()`. Second, the variable name is misleading as the resulting object is a `DocumentFragment`, not a Range. Third, any images in this fragment will be clones of those found in the original range so are unlikely to be useful. Fourth, this won't work in IE.
Tim Down
2010-05-08 14:30:14
@Tim Down, sorry, it was kinda late ;). For points 1, 2 and 3, I've fixed the problems you've mentioned (thanks a lot). Fourth, depending on the importance of your IE audience (corporate internals) I could either say *"do IE hax"* or *"So?"*
Delan Azabani
2010-05-09 01:28:06
As mentioned below, extractContents modifies the document, which wasn't a desirable side effect. I ended up using: `var d = document.createElement("div"); d.appendChild(window.getSelection().getRangeAt(0).cloneContents()); var img = $("img", d);`. Since I didn't need to modify the elements, I could have also used bortao's Regexp suggestion.
CyberShadow
2010-05-09 07:58:42
+1
A:
it seems to entirely lack any support for selection or DOM ranges
Yeah, the reason for that is IE lacks support for selection and DOM Range. You can build an abstraction layer on top of IE's non-standard ‘TextRange’ objects, but due to the extremely poor interface exposed by TextRanges it's difficult, slow and complicated enough that it's a full-on library in itself. See eg. this one.
bobince
2010-05-08 09:41:20
On a lighter note, is this meant to be surprising? Does IE support *any* modern technologies? Hello, XHTML? Anyone there? ;)
Delan Azabani
2010-05-09 08:38:48
IE9 supports XHTML! So we'll be able to use that in, ooh, ten years. Woohoo!
bobince
2010-05-09 09:36:39
+1
A:
$("img", window.getSelection().getRangeAt(0).extractContents());
Unfortunately you will have to use the aforementioned IERange library to support IE 6/7/8.
Noteworthy: DOM Range will be implemented in IE9 and there are talks of new selection APIs in HTML5
Josh Stodola
2010-05-09 01:36:39
Doesn't seem to work. The resulting object's size() is always zero. Also, extractContents modifies the document (it *moves* the contents of a Range into a DocumentFragment).
CyberShadow
2010-05-09 07:13:30