I’m using window.getSelection () to get the selected text.
But, if i select an image too, it returns also altof an image.
EXAMPLE:
<img src="someSrc.jpg" alt="image_alt" /> My text here ...
if i select an image too, it returns
image_alt My text here …
But i need only
My text here …
Is there any way to get only text, without alt?
Thanks much
The easiest way would be to use the
toString()method of selection’s Range(s), which is whatwindow.getSelection().toString()is specified to do in the current version of WHATWG’s new Range spec (although this is contrary to what some browsers do and may or may not change). The following will work with multiple selected ranges (which Mozilla supports) and also in IE < 9.jsFiddle: http://jsfiddle.net/timdown/HkP2S/
Code:
UPDATE
This solution includes text inside
<script>and<style>elements. To remove this, you could usecloneContents()on the selection ranges and traverse the DOM of the resulting document fragments, collecting text only from text nodes not contained within<script>and<style>elements. You could also expand on this to remove text that is inside elements with CSSdisplay: none.jsFiddle: http://jsfiddle.net/timdown/HkP2S/2/
Code: