How to access elements in a DOM with JavaScript?

DOM API provides different methods to access elements in a document, via JavaScript. The following are the methods available.

DOM API provides different methods to access elements in a document, via JavaScript. The following are the methods available:

GetElementById()

returns the element that is identified by the passed Id attribute or null if no element matches the passed Id.

Example –

document.getElementById("emailAddress") 
returns the element which is identified by "emailAddress"

getElementsByClassName()

returns a list of elements in the document which contain the passed className or null if no element matches.

Example –

document.getElementsByClassName("myClass") 
returns all the elements which have the className "myClass"

getElementsByTagName()

returns a list of elements in the document which have the passed tag name or null if none match.

Example –

document.getElementsByTagName("p") 
returns all the paragraph tags present in the document.

document.querySelector()

returns the FIRST element that satisfies the passed query selector.

Example –

document.querySelector("div.heading") 
returns the FIRST div that has the class "heading"

document.querySelectorAll()

returns a collection of elements that satisfy the passed query selector.

Example –

document.querySelectorAll("li.myClass") 
returns all the li nodes in the document which have the class "myClass"

TL;DR –

  • document.getElementById() – identified by Id
  • document.getElementsByClassName() – identified by className
  • document.getElementsByTagName() – identified by tagName
  • document.querySelector() – first element that satisfies the selector
  • document.querySelectorAll() – all elements that satisfy the selector
Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Privacy Overview
Referbruv

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

3rd Party Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.