Skip to main content

getElementById in JavaScript DOM (Live Playground)

In this tutorial, we will learn how to use the getElementById method in JavaScript to select and manipulate HTML elements by their unique ID attribute. We'll cover the basics of the method and provide sample code with explanations.

What is getElementById?

The getElementById method is a built-in JavaScript DOM method that allows you to select an HTML element by its id attribute. The method returns the first element with the specified ID, or null if no element with the given ID is found. It is a convenient way to access specific elements in your HTML document and perform various operations, such as modifying content or applying styles.

Sample Code: Using getElementById

Let's say we have the following HTML document:

<!DOCTYPE html>
<html>
<head>
<title>getElementById Example</title>
</head>
<body>
<h1 id="mainHeading">Welcome to My Web Page!</h1>
<p id="introParagraph">This is an introductory paragraph.</p>
</body>
</html>

To use getElementById to select an element, you'll need to include a JavaScript <script> tag in your HTML document. For this example, we will add an inline script, although it's generally recommended to use external JavaScript files for larger projects.

Here's how you can select the h1 element with the ID mainHeading and change its text content:

<!DOCTYPE html>
<html>
<head>
<title>getElementById Example</title>
</head>
<body>
<h1 id="mainHeading">Welcome to My Web Page!</h1>
<p id="introParagraph">This is an introductory paragraph.</p>

<script>
// Select the h1 element with the ID "mainHeading"
var mainHeading = document.getElementById('mainHeading');

// Change the text content of the selected element
mainHeading.textContent = 'Welcome to My Updated Web Page!';
</script>
</body>
</html>

After running this code, the text content of the h1 element with the ID mainHeading will be updated to "Welcome to My Updated Web Page!".

Live Playground, Try it Yourself

Conclusion

The getElementById method is a powerful and convenient way to select and manipulate HTML elements by their unique ID attribute. By mastering this method, you can easily access and modify specific elements in your HTML documents, enabling you to create dynamic and interactive web pages.