20

In the popup window, selText does have the value "great," but the length is always undefined. Something related with the encoding of the string?

var selText = document.getSelection(); //suppose "great" is selected
alert( "selected ->" + selText + " len is " + selText.length);

3 Answers 3

32

Because you're getting a DOM selection object instead of a String. To get the text, call toString().

var selText = document.getSelection().toString();

The reason the string successfully shows up in the alert, is that the concatenation causes an implicit toString() to occur.

Sign up to request clarification or add additional context in comments.

Comments

1

The MDN documentation states.

In the above example, selObj is automatically "converted" when passed to window.alert. However, to use a JavaScript String property or method such as length or substr, you must manually call the toString method.
-- https://developer.mozilla.org/en/window.getSelection

It's suggesting you call document.getSelection().ToString().length;

1 Comment

The function the MDN docs are referring to is window.getSelection(), not document.getSelection(), which is not universally supported and now replaced in all current browsers by window.getSelection(). Also, it's toString() rather than ToString().
0

Deprecated method document.getSelection() Try use window.getSelection().

var selText = window.getSelection().toString();
        if(selText)
        {
            alert( "selected ->" + selText + " len is " + (selText.length - 1));
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.