In JavaScript, I can set t...">

JavaScript document.getElementById ("id") and id attribute

I have:

<div id="myDiv1"></div> <div id="myDiv2"></div> 

In JavaScript, I can set the innerHTML div by writing:

 myDiv1.innerHTML = "myDiv1, Hi!" 

or

 document.getElementById("myDiv2").innerHTML = "myDiv2, Hi!" 

Why should I use document.getElementById when I can just use the element id? Does it work every time or only in some special scenarios (for example, a simple pattern)?

thanks,

Mike

+5
source share
2 answers

Why should I use document.getElementById when I can just use the element id?

To avoid conflicts. The global namespace in browsers is incredibly crowded, there are all sorts of things, including (as you already found) global values ​​that refer to any element with id (the so-called "automatic global variables").

On the contrary, getElementById does just what it says, finds the element with its id ; he is more limited. (Except for bugs in older versions of IE that also looked at elements with name attributes.)

+7
source

when you write

 myDiv1.innerHTML = "myDiv1, Hi!" 

you call the window object, so the actual call is like this

 window.myDiv1.innerHTML = "myDiv1, Hi!" 

This behavior is no longer recommended and should be avoided. Instead, we should use

 document.getElementById` 
+1
source

Source: https://habr.com/ru/post/1212693/


All Articles