Syntax of getElementById() Method
It’s a method of the document object. The method takes a parameter in the form of an element’s id. For example, if you have a paragraph element on your web page, which also have an id, your code should look like this.
<html> <body> <p id="msg">This is a paragraph.</p> </body> <script> const msg = document.getElementById('msg'); // Get the element with id "msg". document.write(msg); // Write the element's property. </script> </html>
Please make sure the ID’s you assign to the elements on your web page are unique. No element should have the same id.
Here’s an example.
In the above example, I have four different elements. Out of which only 3 have ids and all are unique.
In the <script> section, I have used the getElementById() method twice:
The first method has the id (your_name) of an input box of type text. I am using the method with another property called value, to extract the value of the input box.
The second method has the id of a <p> element. Here, I am actually manipulating or changing the content of the element.
Same method, different purpose
Remember, if you have assigned an id to the getElementById() method that does not exist in your web page, then it will return a null. In this case, the browser’s console window will show you an error. For example,
<html> <body> <p> See the console window (Shift+Ctrl+i) for the error. </p> <div id="container"> </div> </body> <script> let cont = document.getElementById('container1'); // The id container1 does not exist. cont.innerHTML = 'Hello!'; // So, it will throw an error here. </script> </html>
Uncaught ReferenceError: getElementById is not defined
Be careful with the capitalization part of the method. It is case-sensitive.