What is the getElementByID method() in JavaScript?

Key takeaways:

  • The getElementById() method in JavaScript allows us to directly access and manipulate individual elements in an HTML document by their unique id.

  • We can use it with this syntax: document.getElementById("elementID")

  • The method accepts a single parameter—the ID of the element—and returns the corresponding element.

  • If the specified ID does not exist, getElementById() returns null, which is helpful for checking if the element exists before applying changes.

Imagine we want to change the text of a specific heading or modify the color of a button when it’s clicked. How can we pinpoint that exact element in our code? JavaScript’s getElementById() method is a straightforward way to access and manipulate individual elements within the DOM by using their unique IDs. Let’s dive in to understand how this works.

What is getElementById()?

The getElementById() method is a part of the JavaScript Document Object Model (DOM) that allows us to access an HTML element with a specified ID. When we use getElementById(), JavaScript scans the document and returns the element with the matching ID. This method is frequently used to manipulate specific elements by changing their styles, content, or attributes. The name of the id is passed as a parameter, and ​the corresponding element is the return value.

Syntax

The syntax for getElementById() is simple:

document.getElementById("id");

Where:

  • Parameter: The id parameter is a string representing the unique ID of the element we want to access.

  • Return value: This method returns the element object with the specified ID. If no element with the specified ID exists, it returns null.

Accessing an element with getElementByID()

Let’s start with a simple example where we access and modify an element’s text.

<!DOCTYPE html>
<html>
<head>
<title>Set Custom Message</title>
</head>
<body>
<h2>Enter your message:</h2>
<input type="text" id="userMessage" placeholder="Type your message here" value="This is the updated message">
<button onclick="displayMessage()">Set Message</button>
<h3 id="display">Your message will appear here...</h3>
<script src="script.js"></script>
</body>
</html>
A basic HTML structure for the application

In the above code:

  • Line 9: We create an input field with the ID userMessage where the user can type their custom message.

  • Line 10: The button triggers the displayMessage() function when clicked.

  • Line 12: The <h3> element with the ID display is where the user’s message will be shown.

Let’s now use the getElementById() method in the JavaScript logic.

function displayMessage() {
// Access the input element and retrieve the user's message
var message = document.getElementById("userMessage").value;
// Access the display element and set its content to the user's message
var displayElement = document.getElementById("display");
displayElement.innerText = message;
}
The JavaScript logic for accessing element using the getElementById() method

The displayMessage() function gets the value entered by the user in the input field (userMessage). Inside this method:

  • Line 3: We get the input field element using the getElementById("userMessage") method and store the value in the message variable.

  • Line 6: We get the heading element using the getElementById("display") method and store it in the displayElement variable.

  • Line 7: We then set the message as the innerText of the displayElement element to display the user’s message on the screen.

Application demo

Now, when a user types a message in the input field and clicks the “Set Message” button, the text will dynamically appear below in the <h3> element, demonstrating how getElementById() helps us capture and display user input.

  • HTML
  • JavaScript
Code example of using getElementById() method

Working with styles using getElementById()

We can also use getElementById() to modify an element’s styling directly. Here’s an example of how to change the color of a button:

  • HTML
  • CSS
  • JavaScript
Example of working with styles using the getElementById() method

In the above JavaScript logic:

  • Line 1: We define a one-liner arrow function named getRandomRgbColor() to get the random color.

  • Lines 3–6: We define the changeColor() function to change the button color. Inside this function:

    • Line 4: We get the button element using the getElementById("myButton") method and store it in the button variable.

    • Line 5: We call the getRandomRgbColor() to get a random color and assign it to the background color of the button element.

Important points to remember

Here are some important points to keep in mind regarding IDs in JavaScript:

  1. ID uniqueness: An ID should be unique within an HTML document. Using the same ID for multiple elements can lead to unpredictable behavior.

  2. Case-sensitive: IDs are case-sensitive, meaning myID and MyId would be treated as separate IDs.

  3. Returns null if not found: If the getElementById() method doesn’t find an element with the given ID, it will return null.

Common use cases of getElementById()

Here are some common use cases of using the getElementById() method:

  • Updating content: Changing text or HTML content dynamically based on user actions.

  • Changing styles: Modifying CSS properties directly through JavaScript.

  • Event handling: Accessing an element to attach or modify events.

Knowledge test

Let’s attempt a short quiz to assess your understanding.

Q

What is the correct syntax to access an element with the ID header?

A)

document.getElementByClass("header");

B)

document.getElementById("header");

C)

document.getElementsById("header");

D)

document.querySelector("#header");

Conclusion

The getElementById() method is a fundamental tool in JavaScript for selecting and manipulating elements by their unique IDs. It’s widely used in DOM manipulation, allowing us to update content, style elements, and handle events dynamically. Whether you’re creating interactive buttons or updating content based on user inputs, understanding getElementById() will serve as a solid foundation for DOM interaction.


Frequently asked questions

Haven’t found what you were looking for? Contact Us


How to access form elements using the getElementById() method

To access form elements using the getElementById() method, assign a unique id to each form element (such as an input field, button, or select box) in the HTML. Then, use document.getElementById("elementID") in JavaScript to retrieve the element. For example:

<form>
  <input type="text" id="username" placeholder="Enter your name">
</form>
<script>
  const usernameField = document.getElementById("username");
  console.log(usernameField); // Logs the input element with id 'username'
</script>

This allows you to manipulate form fields directly, such as reading or setting values, attaching event listeners, or modifying styles.


How to get an item by ID in JavaScript

To get an item by ID in JavaScript, use the getElementById() method, which retrieves the first element in the DOM with the specified id. For example:

<p id="greeting">Hello, World!</p>
<script>
  const greetingElement = document.getElementById("greeting");
  console.log(greetingElement); // Logs the paragraph element with id 'greeting'
</script>

The greetingElement variable now holds a reference to the <p> element, allowing you to access its properties or modify it directly in your script.


How to get a value with ID in JavaScript

To get the value of an element with a specified ID, use getElementById() to access the element, then retrieve its value property (especially for input fields). For example:

<input type="text" id="username" value="John Doe">
<script>
  const usernameValue = document.getElementById("username").value;
  console.log(usernameValue); // Logs 'John Doe'
</script>

Here, usernameValue retrieves the text entered in the input field. For non-input elements, you can use .textContent or .innerText to get their displayed content.


Free Resources

Copyright ©2024 Educative, Inc. All rights reserved