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

Buy Me A Coffee

Found this article helpful? Please consider supporting!

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.

Leave a Reply

Your email address will not be published. Required fields are marked *