YogeshChauhan.com

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

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.

dreamhost

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 uninstall Cocoapods from the Mac OS? #4 How to Use SQL MAX() Function with Dates? #5 How to add Read More Read Less Button using JavaScript? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Apr 7 Solution for “Yarn build: Failed because of a stylelint error” Apr 7 Make sure your links have descriptive text Apr 7 How to add Laravel to WordPress using Sage theme (and install Tailwind CSS)? Apr 2 How to create a sidebar using pure CSS? Apr 1 How to switch dark and light themes using pure CSS? Apr 1 How to calculate elapsed time in JavaScript?

You might also like these

How to verify your domain in Google Console with a TXT record?MiscHow to Display Related Posts in WordPress?WordPressImplicit and Explicit Joins in Oracle SQLSQL/MySQLWhat is ECMAScript?JavaScriptIntroduction to components and templates Part 2: Templates and viewsAngularHow to read Standard Input in Swift?SwiftDebugging in WordPress Part 1: WP_DEBUGWordPressFULL OUTER JOIN in PostgresPostgresIs monitoring an employee’s work on a computer a desirable or undesirable activity?MiscHow to list all PHP variables to debug the script?PHPFor In Loop in Swift for BeginnersSwiftHow to create a pricing table using flex in CSS?CSS