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:
- 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");
- 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
Understanding Document Object Model (DOM) in JavaScript
Understanding HTTP Requests and Responses
What is Asynchronous JavaScript?
JavaScript Code for Event Handling
- AI
- Android
- Angular
- ASP.NET
- Augmented Reality
- AWS
- Bioinformatics
- Biometrics
- Blockchain
- Bootstrap
- C
- C#
- C++
- Cloud Computing
- Competitions
- Courses
- CSS
- Cyber Security
- Data Science
- Data Structures and Algorithms
- Data Visualization
- Datafication
- Deep Learning
- DevOps
- Digital Forensic
- Digital Trust
- Digital Twins
- Django
- Docker
- Dot Net Framework
- Drones
- Elasticsearch
- ES6
- Extended Reality
- Flutter and Dart
- Full Stack Development
- Git
- Go
- HTML
- Image Processing
- IoT
- IT
- Java
- JavaScript
- Kotlin
- Latex
- Machine Learning
- MEAN Stack
- MERN Stack
- Microservices
- MongoDB
- NodeJS
- PHP
- Power Bi
- Projects
- Python
- Quantum Computing
- React
- Robotics
- Rust
- Scratch 3.0
- Shell Script
- Smart City
- Software
- Solidity
- SQL
- SQLite
- Tecgnology
- Tkinter
- TypeScript
- VB.NET
- Virtual Reality
- Web Designing
- WebAssembly
- XML