❮ PreviousNext ❯

In this short tutorial, I’m going to show what are the different ways to access the HTML elements. let’s get started.
1. Get Element by Id
This is the easiest way to find an HTML element in the Document Object Model (DOM) is by using the element id. This example finds the element with their id id="root".
- Get element by id return the only one element. But why, because the id in a CSS selector is unique CSS selector. At the same time, we can’t have multiple ids with the same name.


2. Get Elements by Class Name
It find the collection of HTML elements with the same class name. If we want to find all HTML elements with the same class name, we use getElementByClassName. It does not work in Internet Explorer 8 and earlier versions. Let’s see below Example


3. Get elements by tag name
Another way of finding an element is to get elements by tag name. The following example finds the element by their tag name(h1).
- It finds the collection of HTML elements present in the HTML document to access the individual element we should loop through the element collection.

4. Get Elements by CSS Selectors
It finds all HTML elements that match a specified CSS selector (id, class names, types, attributes, values of attributes, etc), we can use the querySelectorAll() method.
Below example show a list of all div elements with the class name query, in our HTML document we have another one h1 tag with the class query but it ignored and another div with the blank class it also ignored.


5. Get Elements by HTML Object Collections
This example let reg_form = document.forms["register_form"] finds the form element with id form, in the forms collection, and displays all element values:


Thanks for reading
More htmlspacecode