JavaScript getElementById() Method

The getElementById() method returns an element, whose id is passed to the function. This is one of the most commonly used methods in JavaScript. It is often used to extract information about an element or manipulate the contents of an element.

➡️ getElementsByTagName() method

Syntax of getElementById() Method

document.getElementById(element_id);

It’s a method of the document object. The method takes a parameter in the form of an element’s id.

I'll explain this with an example. Let us assume, I have few <p> (or paragraph) elements on my web page and each has a unique id. I want to get a particular P element.

<html>
<body>
  <p id="s1">Content in 1st para.</p>
  <p id="s2">Content in 2nd para.</p>
</body>
<script>
    const el = document.getElementById('s1');    // Get the element with id "s1".
    document.write(el);        // Write the element's property.
</script>
</html>
Try it

The method is case-sensitive. So, be careful when you are typing the method. For example, By cannot be by or Id cannot be ID. However, most JavaScript editors today have built-in intellisense or intelligent code completion feature. Therefore, you need not to worry.

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 another example.

<html>
<body>
    <div>
      <input type='text' id='your_name' placeholder='Enter your name' />
      <input type='button' value='Click it' id='bt' onclick='say_hello()' />
    </div>

    <p id="msg"></p>
</body>
<script>
    let say_hello = () => {
        let name = document.getElementById('your_name').value;
        let msg = document.getElementById('msg');
        msg.innerHTML = 'Hello ' + name + ' 🙂';
	}
</script>
</html>
Try it

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. The method has some propeties. I am using the value property to extract the value (or the content) 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 the error.

For example, I have a DIV element and I want to add some contents to it dynamically. However, I have assigned a "wrong" id to "getElementById()" method and it throws an error.

<html>
<body>
    <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>
Try it

➡️ getElementsByTagName() method