Javascript Reference - HTML DOM getElementById() Method








The getElementById() method returns the element that has the ID attribute with the specified value.

Browser Support

getElementById Yes Yes Yes Yes Yes

Syntax

document.getElementById(elementID)

Parameter Values

Parameter Type Description
elementID String Required. The ID attribute's value of the element




Return Value

An Element Object. Returns null if no elements with the specified ID exists.

Example

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:





Example 2

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: