How it works?

<html> <head></head> <body> <div id=res></div> <script> res.innerText = "Hello, World!" </script> </body> </html> 

UPD. It seemed to me that id can only be a string: id="res" and you can only access the element with this: document.getElementById("res") .

  • Try to write more detailed questions. To get an answer, explain exactly what you see the problem, how to reproduce it, what you want to get as a result, etc. Give a sample code. - Grundy
  • The question is different, why should it not work? - Alexey Shimansky
  • @ Alexey Shimansky did not say that it does not work. He asked to describe why and how. Well, I think so. - Sergalas
  • @Sergalas writes a strange id, which means he thinks he is wrong, so how can the code work with the wrong id? This logic seemed to me) - Alexey Shimansky
  • one
    In HTML, it is not necessary to close all tags; tags and attribute names can be written in any case, quotes are optional. - Alexey Shimansky

2 answers 2

Access to html elements can be obtained directly by their id , i.e. use the form as in your example: res.innerText , where res is the id for this div. This behavior is defined in the standard and is primarily necessary for backward compatibility.

How it works?

It works awfully.

First, getting id into the global namespace, as far as I can imagine, is non-standard (although it may already have been standardized). Some time ago it did not work in FF, now it is normal.

Secondly, innerText is creepy. His cross-browser compatibility is very doubtful, it is non-standard and only appeared in the FF 46 version. And in chrome, where it is originally, even at assignment it is ten times slower than the standard textContent .

 res.innerText = "Hello, World!" 
 document.getElementById("res").textContent = "Hello, World!";