Why, after conversion to a string, shows "23", and not "5"? And the second question is, why toUpperCase () does not display text between tags in capital letters?

var text = document.getElementById('text'); text = text.toString(); alert(text.length); alert(text.toUpperCase()); 
 <div id="text">Lorem</div> 

  • 2
    And what do you want to achieve with this code? Do you understand that you have a dom object in the text variable? If you want to work with text, then get the text var text = document.getElementById('text').innerText; - Pyramidhead
  • Is it not possible to convert an object into a string? - ikar
  • @ikar why, if you expect to get only the text inside the tag ??? - Kirill Korushkin
  • I study! I thought so too can get the text. - ikar
  • @ikar, in fact, the object is completely transformed into a string. Just not the way you expected. - Grundy

2 answers 2

Pyramidhead's comment on the question is exhaustive. I will only write the code:

 var text = document.getElementById('text'); text = text.innerHTML; // тут присваивайте свойство html объекта text, по сути - содержимое тега id="text" alert(text.length); alert(text.toUpperCase()); 
 <div id="text">Lorem</div> 

  • necessary information is transferred from the comment in response - Grundy

If you look at the specification , it can be noted that the toString function, if not overridden, returns a string of the following form:

 [object `tag`] 

Where the tag depends on the type of object and the value of the special property. In this case, the tag is: HTMLDivElement .

The final line is "[object HTMLDivElement]" and it is its length that is output.


To get the text, you need to use one of the properties: innerHTML , innerText , textContent