Definition and Usage
The getElementById() function returns the Element object whose HTML id attribute value matches the specified string. If no matching element exists, it returns null.
Basic Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>getElementById() Example</title>
</head>
<body>
<p id="hello">Welcome! Nice to meet you!</p>
<script>
const changeColor = newColor => {
const element = document.getElementById("hello"); // Finds the element with id="hello".
element.style.color = newColor;
}
</script>
<button type="button" onclick="changeColor('red');">Change to Red</button>
<button type="button" onclick="changeColor('blue');">Change to Blue</button>
</body>
</html>
Syntax
document.getElementById(id);
Return Value
- Returns the element (Element) object whose HTML id attribute value matches the specified string.
- Returns null if no matching element exists.
Things to Keep in Mind
# Preventing Errors When the Target Element Does Not Exist
The getElementById() function returns null if the element to find does not exist.
# The Value of the Target Element's id Attribute Is Case-Sensitive
The id parameter of the getElementById(id) function is a case-sensitive string.
# getElementById() Is Only a Method of the document Object
The getElementById() function is a document-only method used to find elements based on the entire HTML document.
Therefore, it cannot be used on Element objects accessed through properties such as parentNode and parentElement.
Top comments (0)