How to Access an Element in HTML DOM using JavaScript?

Element Access Methods

MethodDescription
document.getElementById(“ID”)Get the element with the specified ID
document.getElementsByTagName(“Tag_Name”);Get all the specified element by the Tag Name
document.getElementsByClassName(“Class_Name”);Get all the specified element by the Class Name
document.querySelector(“CSS_Selector”);It returns the first match of the passed selector string
document.querySelectorAll(“CSS_Selector”);It returns a node list of DOM elements that match the query

getElementById(“ID_Name”)

The method getElementById(“ID_Name”) returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they’re a useful way to get access to a specific element quickly.

getElementsByTagName(“Tag_Name”)

The method getElementsByTagName(“Tag_Name”) returns a live node list meaning that it updates itself with the DOM tree automatically, so modification of the DOM tree will be reflected in the returned collection. The returned Node List or Collection of Nodes can be accessed by index numbers starting with index 0.

  • This method accepts a string indicating the type of elements that be retrieved, a special value “ * ” returns all elements in the documents.
  • You can use the length property of the NodeList object to determine the number of elements with the specified tag name, then you can loop through all elements and extract the info you want.

getElementsByTagName(“Tag_Name”)

getElementsByTagName(“Tag_Name”)

More specific

getElementsByTagName(“Tag_Name”)

  • Length Property
  • Loop

getElementsByClassName(“Class_Name”)

The Method getElementsByClassName() returns a live node list meaning that it updates itself with the DOM tree automatically, so modification of the DOM tree will be reflected in the returned collection. The returned Node List or Collection of Nodes can be accessed by index numbers starting with index 0.

•This method accepts string indicating the class name of elements that be retrieved •

We can also pass multiple class name. For matching, all the class names should match. •You can use the length property of the NodeList object to determine the number of elements with the specified class name, then you can loop through all elements and extract the info you want.

  • This method accepts string indicating the class name of elements that be retrieved
  • We can also pass multiple class name. For matching, all the class name should match.
  • You can use the length property of the NodeList object to determine the number of elements with the specified class name, then you can loop through all elements and extract the info you want.

getElementsByClassName(“Class_Name”)

getElementsByClassName(“Class_Name”)

More specific

getElementsByClassName(“Class_Name”)

  • Length Property
  • Loop
Tagged : / / /