Flat Preloader Icon

getElement by ID

In JavaScript, the getElementById method is used to retrieve an HTML element from the DOM (Document Object Model) based on its unique ID attribute. Here’s how it works:
					var element = document.getElementById(id);


id: This is a string parameter that represents the unique ID attribute of the HTML element you want to retrieve.

Return Values

It returns a reference to the HTML element with the specified ID. If no element with the given ID exists, it returns null.

Once you have the reference to the element, you can manipulate it in various ways, such as changing its content, style, or behavior.
					<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <div id="myDiv">Hello, world!</div>
    <script src="script.js"></script>


JavaScript (script.js):

					// Retrieving the element with id "myDiv"
var element = document.getElementById("myDiv");

// Manipulating the element
element.innerHTML = "Goodbye, world!";
element.style.color = "red";

In this example, the JavaScript code retrieves the div element with the ID “myDiv”, then changes its content to “Goodbye, world!” and its text color to red. Keep in mind that IDs should be unique within the HTML document. If multiple elements have the same ID, getElementById will only return the first matching element. Also, note that the method is case-sensitive.

Share on: