YogeshChauhan . com

How to get the first element with a class name xyz using JavaScript?

in JavaScript on March 16, 2021

We can use getElementsByClassName to get all the elements with a class name ‘xyz’. We can also use document.querySelector and document.querySelectorAll to get elements with a class name ‘xyz’.

We can use getElementsByClassName(“xyz”)[0] ot get the first element with a class name ‘xyz’.

Here is how to do it:

One more way to do is using the querySelector() method. When we use querySelector() method on multiple elements, it will only return the first element that matches the query.

Here’s how to do it:

There is another way to do it.

We can add a parent element for all those elements with class name ‘xyz’. Then we’ll add id attribute for the parent element whose child element we want to target it and then use the id and class both to target the element.

It’s just a long way but for the sake of the example, let’s check it out.


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

Window innerHeight and innerWidth properties in JavaScriptJavaScriptA Step by Step Guide to Make RSS in XML For Any Website or Blog For FreeMiscHow to check if the element exists using JavaScript and jQuery?JavaScriptHow to Install PHP Laravel on MacOS Catalina?PHPThe Difference Between Arrays and Objects in JavaScriptJavaScriptThe Drupal flowDrupalHow to add a ribbon on top of a container using CSS?CSSNumber Properties in JavaScriptJavaScriptHow to add a Pie Chart in Angular App?AngularHow to add Date and Time picker in HTML and get the values using JavaScript?HTMLHow to refresh a page using PHP at regularly occurring intervals?PHPHow to concatenate variable with string in Swift?Swift