Yogesh Chauhan's Blog

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 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
A few HTML coding standards from WordPressHTMLHow to use data-* Attributes in HTML?HTMLUseful (and probably ignored) HTML tags: Part 2HTMLLearn how to add Scroll Indicator using CSS and JavaScript?CSSUPDATE and DELETE Statements in PostgresPostgresCROSS JOIN in PostgresPostgresWhat is iFrame in HTML? Why do we need it?HTMLHow to create a circle that follows a cursor using JavaScript and CSS?CSSHow to check if a link has http or https in it in JavaScript?JavaScriptHTML Copyright SymbolHTMLAt-rules: @error and @warn in SCSSSCSSSocial Media Colors: Sass VariablesMiscellaneous