JavaScript getElementById
The getElementById method is one of the most commonly used methods in JavaScript. It is used to retrieve an element from the HTML document based on its unique identifier (ID).
Syntax
document.getElementById(id)
document
: A reference to the document object.getElementById
: Method used to retrieve an element based on its unique ID.id
: A string value which represents the ID of the desired HTML element.
Example
Suppose we have an HTML document with the following code:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript getElementById Example</title>
</head>
<body>
<h1 id="mainHeading">Hello World</h1>
<p id="para1">This is a paragraph.</p>
<button id="myButton" onclick="changeText()">Change Text</button>
<script src="script.js"></script>
</body>
</html>
We can retrieve the element with ID "mainHeading" using the following JavaScript code:
var heading = document.getElementById("mainHeading");
Output
The above JavaScript code will return a reference to the HTML element with ID "mainHeading". We can use this reference to access or manipulate its properties and methods.
For example, to change the text of the "mainHeading" element, we can use:
heading.innerHTML = "New Heading Text";