Online Forum To Support Coders With Technical Assistance - Read Write Execute

How to find HTML Elements using JavaScript?

Aman Agrawal
Aman Agrawal
Published on August 8, 2015 · 2 min read

So as we know Java Script can do any manipulation,validation to our static HTML elements.But , the question is how ร‚ย this weak type language is accessing our HTML.

To the beginners it is the common trend to use the ID for the particular HTML elements.e.g.

var theElement = document.getElementById("main");

where the id “main” is actually the ID of the desired HTML element as below:-


<div id="main"></div>

But the question comes into my mind whether there exists any other methods.
Like in CSS if we have to apply the styling any element we could use either tag, ID or class or all.

So answer is yes. we can select the HTML elements by following methods:-

  1. by id
    by tag name
    by class name
    by CSS selectors

1. getElementById : by id

var theElement = document.getElementById("main");

2. getElementsByTagName : by tag name

var theElement = document.getElementsByTagName("div");

3. getElementsByClassName: by Class Name

var theElement = document.getElementsByClassName("myClass");

4. querySelectorAll(): by CSS Selectors:-

finding all HTML elements that matches a specified CSS selector (id, class names, types, attributes, values of attributes, etc), use the method.

var x = document.querySelectorAll("p.myClass");
Was this article helpful?
Aman Agrawal

Aman Agrawal

Author & Senior Engineer at CodeExecute

Writing practical engineering guides, debugging real-world bottlenecks, and creating free tools for developer productivity.

← Previous Article How to get current user role in wordpress Next Article → Bootstrap – A great Hack for Front End developers