JavaScript

How to Access HTML Elements in JavaScript Using ID and Class

In this article, I will explain How to Access HTML Elements in JavaScript Using ID and Class.

In order to access HTML elements in JavaScript using their ID and class you can use the following methods:

  1. Using ID. For the purpose of accessing an element with a specific ID, you can use the document.getElementById() method. The following example demonstrates it.
let element = document.getElementById("elementID");
  1. Using Class. Likewise, you can access all elements with a specific class using the document.getElementsByClassName() method. The following example demonstrates it.
let elements = document.getElementsByClassName("className");

Note: The getElementsByClassName() method returns an HTMLCollection, not an array, so you need to use the item() method or convert it to an array to access individual elements. The following example demonstrates it.

let elements = document.getElementsByClassName("className");
let firstElement = elements.item(0);

Further Reading

Evolution of JavaScript from ES1 to ES2020

Introduction to HTML DOM Methods in JavaScript

JavaScript Practice Exercise

Understanding Document Object Model (DOM) in JavaScript

Understanding HTTP Requests and Responses

What is Asynchronous JavaScript?

JavaScript Code for Event Handling

Princites

You may also like...

Leave a Reply

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