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 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Effects in ReactReactHow to check if a link has http or https in it in JavaScript?JavaScriptHow to use $INSERT command in Envision Basic?Envision Basic3 Common Usability Mistakes In Web DesignUI/UXAlternate Style Sheets in CSSCSSPHP Variables ScopePHPWhat are partials in SCSS (Sass)?SCSSFile System Integrity: How to Keep an Eye on Your Files and Folder Change?MiscellaneousHow to obfuscate JavaScript code to hide it from View Source?JavaScriptWhat’s a Log File and What are Log File Monitors?MiscellaneousKanban vs Scrum: The two frameworks of agile principlesMiscellaneousThe difference between 400(4xx) and 500(5xx) errorsMiscellaneous