javascriptstring

Why does string.length return undefined?


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);

Solution

  • 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.