Delgan
Delgan

Reputation: 19677

Why using getRangeAt() removes some content from selection, in JavaScript?

Using Firefox, I can use window.getSelection() in order to get the selected text.

If I selected an image, the alt attribute is returned.

However, if I use .getRangeAt(0), the selection is returned without the alt attribute.

I would like it to be present in my variable, how can I solve this problem, please?

You can try it here: http://jsfiddle.net/Q982A/56/

If you select the whole line, Hello. :) is printed first, and then Hello..

Upvotes: 2

Views: 548

Answers (1)

Samuel Caillerie
Samuel Caillerie

Reputation: 8275

How do you want to use this range? A range is an object whose toString method is the inner text (see MDN doc - Range.toString) and not inner HTML which is displayed.

Nevertheless, you have the whole selection in this object and you can visualize it with by creating a fragment with it, for example like this :

var sel = window.getSelection();
var selRange = sel.getRangeAt(0);
document.getElementById("test").appendChild(selRange.extractContents());

See this fiddle.


EDIT :

You can also use a document fragment like this : http://jsfiddle.net/Q982A/66/ (in order not to use a displayed element)...

Upvotes: 1

Related Questions