Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript document.getElementById(“id”) and element id attribute

Tags:

javascript

dom

I have:

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

In JavaScript, I can set div innerHTML by writing:

myDiv1.innerHTML = "myDiv1, Hi!"

or

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

Why should I use document.getElementById when I can simply use element Id ? Is this working every time or only in some special scenarios (like simple sample)?

thanks,

Mike

like image 358
mike m Avatar asked Feb 05 '15 10:02

mike m


People also ask

What is an element id in JavaScript?

The id property of the Element interface represents the element's identifier, reflecting the id global attribute. If the id value is not the empty string, it must be unique in a document. The id is often used with getElementById() to retrieve a particular element.

Why do we use document get element by id?

getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

How do I get the document id in getElementById?

HTML DOM Document getElementById()The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM.


1 Answers

Why should I use document.getElementById when I can simply use element Id ?

To avoid conflicts. The global namespace on browsers is incredibly crowded, all sorts of things are dumped in there, including (as you've found) globals referring to any element with an id (so-called "automatic globals").

In contrast, getElementById only does what it says, finds an element by its id; it's more constrained. (Other than bugs in old versions of IE, which also looked at elements with name attributes.)

like image 152
T.J. Crowder Avatar answered Sep 28 '22 08:09

T.J. Crowder