getElementById
Summary
Gets an element with a specified ID.
Method of dom/Documentdom/Document
Syntax
var element = document.getElementById(id);
Parameters
id
- Data-type
- String
The ID to match.
Return Value
Returns an object of type DOM NodeDOM Node
An element that matches the specified ID. If there are multiple matches, the first is returned. If there is no match, null
is returned.
Examples
The following example uses getElementById to display the content of the first div element in a collection with the ID attribute value, div1
, when a button is clicked.
<!doctype html>
<html>
<head>
<title>"Show First DIV Content"</title>
<meta charset="utf-8"/>
<script type="text/javascript">
function getID() {
// Display the content of the first DIV element in the collection.
var div = document.getElementById("div1");
alert("The content of the first DIV element is " + "\"" + div.innerHTML + "\".");
}
</script>
</head>
<body>
<div id="div1">Div #1</div>
<div id="div2">Div #2</div>
<div id="div3">Div #3</div>
<input type="button" value="Show First DIV Content" onclick="getID()">
</body>
</html>
Related specifications
- DOM Level 2 Core
- Recommendation
- DOM Level 3 Core
- Recommendation
- W3C DOM4
- Candidate Recommendation
Attributions
Microsoft Developer Network: Article