Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all <img> tags inside a text selection?

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?

like image 595
Vladimir Panteleev Avatar asked May 08 '10 08:05

Vladimir Panteleev


2 Answers

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.

like image 159
Delan Azabani Avatar answered Oct 07 '22 00:10

Delan Azabani


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.

like image 31
bobince Avatar answered Oct 07 '22 00:10

bobince