In JavaScript, the getElementById() method is used to select an HTML element based on its unique id attribute. It provides a simple way to access and manipulate specific elements on a web page.
- Selects an element using its unique id.
- Returns the matching element or null if no element is found.
- Allows you to modify an element's content, styles, and attributes.
Approach: Using getElementById() Method
The document.getElementById() method searches the document for an element with the specified id and returns that element.
Syntax:
document.getElementById(id);Example: In this example, we use getElementById() to select an element and display its text in the console.
<!DOCTYPE html>
<html lang="en">
<body>
<h1 id="gfg">GeeksforGeeks</h1>
<script>
const gfg = document.getElementById("gfg");
console.log(gfg.innerText);
</script>
</body>
</html>
The getElementById() method is commonly used when you need to access a specific element and perform operations such as updating its content, changing its style, or modifying its attributes.
Output:
