Getting DOM Elements using JavaScript

Getting DOM Elements using JavaScript

In this tutorial, we will learn how to use JavaScript to access different nodes (HTML elements) in the DOM. The Document Object Model (DOM) is a programming interface for HTML and XML documents created by the browser once the document is loaded. A web page is essentially a document represented by the DOM as nodes and objects. It allows programs to manipulate the document's content, structure, and styles.

The Document Object Model (DOM) is a programming interface for HTML and XML documents created by the browser once the document is loaded. A web page is essentially a document represented by the DOM as nodes and objects. It allows programs to manipulate the document's content, structure, and styles.

In this tutorial, we will learn how to use JavaScript to access different nodes (HTML elements) in the DOM. Let us start with the first method: getting element by ID.

Get Element By ID

The docuemnt's getElementById() method takes the element ID as input and returns an Element object representing the DOM element. Here is an example:

<div id="unicorn">🦄</div>

Now here is how we can get the above <div> element by using its ID:

const unicorn = document.getElementById('unicorn');

The ID is case-sensitive and unique across the entire HTML document. So this method always returns a single element. If no matching element is found, it returns null.

Note: Do not put the # sign before the ID string while calling getElementById() method. You will get null instead of the element, and then you might wonder for hours what went wrong.

Get Elements By Tag Name

The getElementsByTagName() method is used to access multiple elements. It takes the tag name as input and returns all of the DOM elements that match the tag name as HTMLCollection:

<p>🐱</p>
<p>🐰</p>
<p>🐯</p>
<p>🐧</p>

JavaScript code to access all <p> elements:

const animals = document.getElementsByTagName('p');

This method searches only one tag name at a time. But if you pass in * as the tag name, you will get all elements in the DOM:

const allNodes = document.getElementsByTagName('*');

Get Elements By Name

The getElementsByName() method is used to get a collection of elements by their name attribute, and returns a NodeList object:

<input type="text" name="email">
<input type="tel" name="phone">
<input type="date" name="dob">

Let us get all the elements with the name email:

const emails = document.getElementsByName('email');

Note: Unlike the id attribute, which must be unique, multiple HTML elements can have the same name attribute. That's why getElementsByName() returns a collection of nodes.

Get Elements By Class Name

Want to use class attribute to get a list of matching elements? You can use getElementsByClassName() method, just pass it a class name (without .) and it will return an HTMLCollection of all DOM elements that have the given class name:

<div class="bird owl">🦉</div>
<div class="bird">🐦</div>
<div class="bird eagle">🦅</div>
<div class="animal cat">🐱</div>

Let us get all the bird's:

const birds = document.getElementsByClassName('bird');

This method also accepts multiple class names separated by spaces. Let us get all elements that have both the bird and eagle classes:

const eagle = document.getElementsByClassName('bird eagle');

Query Selector

The querySelector() is one of the two modern JavaScript methods that allows you to get elements from DOM based on CSS selectors. Just pass in the CSS selector and you will get the first element that matches the specified selector. If no matches exist, it returns null. Here is an example:

const email = document.querySelector('#signup input[name="email"]');

Query Selector All

Want to select a list of elements that match the specified selectors? Use querySelectorAll() method instead. This method takes multiple CSS selectors as input and returns a NodeList - a list of DOM elements that match the given selectors. Let us select all elements with a class of either bird or animal from the above HTML markup:

const elems = document.querySelectorAll('.bird, .animal');
console.log(elems.length); // 4

Function Chaining

You can also chain multiple functions together to search elements within another element. You first need to select a single element using either getElementById() or querySelector(), and then chain another function to search within:

<form id="signup">
    <input type="text" name="email">
    <input type="tel" name="phone">
    <input type="date" name="date-of-birth">
</form>

Get all input elements, inside of an element that has the ID signup:

const inputs = document.getElementById('signup').getElementsByTagName('input');
// OR
const inputs = document.querySelector('#signup').querySelectorAll('input');

Traversing HTMLCollection and NodeList

Most of the methods we discussed above (except getElementById() and querySelector()) returns multiple elements as either an HTMLCollection or a NodeList.

The HTMLCollection is not an array but a generic collection of elements. So it is not possible to iterate over it with forEach() or map(). However, we can convert it to a real array and then iterate using Array.from() method:

const inputs = document.getElementById('signup').getElementsByTagName('input');
// iterate over HTMLCollection
Array.from(inputs).forEach(element => {
    console.log(element);
});

Although NodeList is also not an array, but it does provide forEach() method to iterate over the elements:

const inputs = document.querySelector('#signup').querySelectorAll('input');
//iterate over NodeList
inputs.forEach(element => {
    console.log(element);
});

Conclusion

That's all for getting DOM elements using JavaScript. We have learned so many different methods to access the DOM elements: using id attribute, HTML tag name, name attribute, class attribute and CSS selectors. We also discussed ways to iterate over the generic collection of elements returned by these methods.

javascript html

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Know Everything About HTML With HTML Experts

HTML Assignment Help Australia @30% OFF from Sample Assignment, with Our Best HTML assignment help experts. Get HTML homework help online at affordable price. 100% Plag free assignment solution.

HTML JavaScript - Add Javascript File to HTML

Learn HTML and javascript, their uses & importance, html javascript function, javascript tags list, why add javascript file to html, HTML Events with JavaScript etc

Commonly Used HTML Tags with Examples

HTML tags are keywords used in HTML to display web-pages with certain properties. They are further used for defining HTML elements. An HTML element consists of a starting tag.

Countdown with HTML, CSS, and JavaScript / How to create JavaScript Countdown

Countdown with HTML, CSS, and JavaScript / How to create JavaScript Countdown. W will build a Responsive Website with HTML, CSS, and JavaScript

Render HTML with Vanilla JavaScript and lit-html

Sometimes you need to render HTML elements on a web page. And like Goldilocks' search for "just right", you have to try a few techniques before you find the right one. Using a framework may be too hard. Using pure HTML and the DOM API may be too soft. What you need is something in the middle that is just right. Is lit-html "just right"? Let's find out.