Advertisement

Google Ad Slot: content-top

JS Access Dom

~1 min read · JS
On this page

JavaScript provides several methods to interact with and manipulate the Document Object Model (DOM). The DOM represents the structure of a web page as a hierarchical tree of elements, and these methods allow you to access specific parts of the document for dynamic updates.


Method

Returns

Live/Static

Use Case

Single element

Live

Best for accessing unique elements by id.

HTMLCollection

Live

Access multiple elements with the same class.

HTMLCollection

Live

Access elements by their tag name.

Single element

Static

Access the first element matching a CSS selector.

NodeList

Static

Access all elements matching a CSS selector.


Accessing by id document.getElementById()

  • Retrieves an element by its unique id attribute.
  • Returns: A single element or null if not found.
Example

Access element by using id

Open console in browser then you will see output

Try it yourself

Accessing by Class document.getElementByClassName()

  • Retrieves all elements with a specified class name.
  • Returns: A live HTMLCollection (like an array, but not exactly).
Example
  • Item 1
  • Item 2
  • Item 3
Try it yourself

Accessing by Tag Name document.getElementByTagName()

  • Retrieves all elements with a specified tag name.
  • Returns: A live HTMLCollection.
Example

Paragraph 1

Paragraph 2

Paragraph 3

Try it yourself

Accessing by CSS Selectors Single Element document.querySelector()

  • Retrieves the first matching element based on a CSS selector.
  • Returns: A single element or null if not found.
Example
Important Not Important
Try it yourself

Accessing by CSS Selectors Multiple Elements document.querySelectorAll()

  • Retrieves all matching elements based on a CSS selector.
  • Returns: A static NodeList (not live).
Example
Important Not Important
Try it yourself

Looping Through Multiple Elements:

When accessing multiple elements (e.g., using getElementsByClassName or querySelectorAll), you can loop through them to perform actions:

Example
  • Item 1
  • Item 2
  • Item 3
Try it yourself