Document.getElementById tutorial

last modified July 10, 2020

Document.getElementById tutorial shows how to find a single element by its Id with Document.getElementById() method in JavaScript.


Document.getElementById() is used to find a single element by its Id. The Id is unique within a document. To find elements that do not have an Id, we can use the querySelector() method.

There are similar methods to retrieve elements including getElementsByTagName(), getElementsByClasName(), and getElementsByName().

Document.getElementById example

The following example demonstrates the usage of the document's getElementById() method.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="main.css">

<div id="mydiv">Some content</div>
<button id="btn">Info</button>

<script src="main.js"></script>

In the example, we have a button which retrieves a div element by its Id and writes some info to the console.

div {
    width: 200px; height: 150px; border: 1px solid steelblue;
    padding: 5px;

button {
    width: 4em; height: 2em;

* {
    margin: 10px 10px;

This is some basic styling for the document.

const el = document.getElementById('mydiv');
const btn = document.getElementById('btn');

btn.addEventListener('click', () => {


We use the getElementById() to get a reference to the div and to the button elements. We add a listener to the button. Upon clicking on the button, we output the div's name and text content.

In this tutorial, we have worked with the document's getElementById() method.

You might also be interested in the following related tutorials: JavaScript queryselector tutorial, Document.all tutorial, Element.classList tutorial, Element.innerHtml tutorial, Document.createElement tutorial, Document.createNodeIterator tutorial, The dataset tutorial, Ramda tutorial, or Counting child elements in DOM.