How to find HTML Elements using JavaScript?

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");