The getElementById()
method returns the element
that has the ID attribute with the specified value.
getElementById |
Yes | Yes | Yes | Yes | Yes |
document.getElementById(elementID)
Parameter | Type | Description |
---|---|---|
elementID | String | Required. The ID attribute's value of the element |
An Element Object. Returns null if no elements with the specified ID exists.
The following code shows how to get the element with the specified ID.
<!DOCTYPE html>
<html>
<body>
<p id="demo">paragraph.</p>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {<!-- w w w .ja v a2s. c o m-->
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to get the element with id="demo" and change its color.
<!DOCTYPE html>
<html>
<body>
<p id="demo">paragraph.</p>
<!--from w ww. jav a2 s . c o m-->
<button onclick="myFunction()">test</button>
<script>
function myFunction() {
var x = document.getElementById("demo");
x.style.color = "black";
}
</script>
</body>
</html>
The code above is rendered as follows: