Skip to content
Home » How to Use JavaScript’s document.getElementById() Function

How to Use JavaScript’s document.getElementById() Function

In this article, we will learn how to use the document.getElementById() function in JavaScript. This function allows us to access HTML elements on a webpage using their unique ID. It is a handy tool for manipulating the content and behavior of various elements. We will walk through the code snippet, explain its purpose, and provide an example to help you understand its implementation.

Code

const $ = id=> document.getElementById(id);

Code Explanation

The provided code snippet showcases a concise implementation of the document.getElementById() function using arrow syntax in JavaScript. Let’s break down the code and understand its functionality.

javascript
const $ = id => document.getElementById(id);

Here, we define a function called “$” using the arrow function syntax. The function takes an “id” parameter, which represents the unique ID assigned to an HTML element. Inside the function body, we utilize the document.getElementById() method to retrieve the element with the specified ID from the webpage’s DOM (Document Object Model). Finally, we return the element, allowing us to store and manipulate it further in our program.

Example Usage:

Suppose we have an HTML page with the following element:

html
<p id="myParagraph">This is a sample paragraph.</p>

To access this paragraph element and perform various operations, we can use the previously defined “$” function as follows:

javascript
const paragraph = $("myParagraph");
paragraph.textContent = "This paragraph has been updated.";
paragraph.style.color = "blue";

In the above example, we first call the “$” function and pass the ID “myParagraph” as an argument. This returns the paragraph element, which we store in the “paragraph” variable. After that, we can modify its text content using the “textContent” property and change the font color using the “style.color” property.

Conclusion

By using the document.getElementById() function in JavaScript, we can easily access and manipulate HTML elements by their unique ID. This allows us to dynamically update the content and style of various elements within a webpage. Understanding and utilizing this function will greatly enhance your ability to interact with the DOM and create dynamic web pages.

Also checkout the following codes.


How to Install node-red-contrib-alexa-local using npm?
How to Center an Element using CSS