Document.getElementById tutorial
last modified August 24, 2023
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.
<!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.
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', () => { 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 article we have worked with the document's getElementById
method.