Ebooks

Document.getElementById tutorial

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

Document.getElementById

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.

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

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

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

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

main.css
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.

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

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

    console.log(el.tagName);
    console.log(el.textContent);
});

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.