/

HTML / CSS / JavaScript Tutorial

JavaScript Document own method: getElementById()

[this page | pdf | back links]

The getElementById() method (when applied to the document object of the JavaScript DOM) returns the element with the specified id attribute (if it exists).

 

It has the following syntax with the following parameters. It returns an element object, representing the element with the specified id as its id attribute or null if no such element exists.

 

document.getElementById(id)

 

Parameter

Required / Optional

Description

id

Required

String specifying the value of the id attribute of the element you want to obtain

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,td,tr,th,caption {border: thin solid black; border-collapse: collapse;}
</style>
</head>
<body>
Click anywhere on the document<br><br>
<table>
  <tr><th>Dom method</th><th>Value returned</th></tr>
  <tr><td>getElementById</td><td id="x1"></td></tr>
  <tr><td>getElementsByName</td><td id="x3"></td></tr>
  <tr><td>getElementsByTagName</td><td id="x4"></td></tr>
</table>
<br>Elements:<br>
<em id="id">A</em><br>
<em>B</em>: <input name="name" alt="B"><br>
<em>C</em><br>

<script>
document.addEventListener("click", addevent, false)

function addevent() {
document.getElementById("x1").innerHTML = 
    document.getElementById("id").innerHTML;
document.getElementById("x3").innerHTML = 
    document.getElementsByName("name")[0].alt;
document.getElementById("x4").innerHTML = 
    document.getElementsByTagName("EM")[2].innerHTML;
}
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodDomGetElementById() {
  return !!document.getElementById;
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript DOM (and BOM)


Desktop view | Switch to Mobile