How to check if a given element has a specified class in JavaScript?
Overview
To perform a certain task first, we need to access that specific element by its class or ID, so before accessing that element, we check if the class exists in that specific element. The classList object contains the built-in method classList.contains() in JavScript. This method determines whether the given element belongs to the specified class. The whole process will happen because first we have to access the element through getElementById(), getElementsByClassName() or any other method. After accessing it we have to check the class using classList.contains() method.
grammar
The syntax used in this question is -
classList.contains(className);
classList - This is an object in JavaScript that receives an array of classes contained in a specific element.
contains - This is a method of classList object that checks whether the specified class is present in the given element.
className - This is the specified name that we have to search for in the given element.
algorithm
Step 1 - Create some HTML elements inside the body tag. Assign some class to each element.
Step 2 - Specify the onclick() event method in the HTML button.
Step 3 - Create a JavaScript arrow function. Access any HTML and store it in a variable.
Step 4 - Use the contains() method of the classList object. Pass variables as arguments to the contains() method.
Step 5 - If it returns true then the specific class exists in the HTML element, else if it returns false then the specific class does not exist in the element.
Example 1: When the element contains the specified class
We used the "
" tag in the body tag, which contains the class name: class = "my-para first lorems", so these are the class names. Our task is to check the element to see if it contains the specified element. To do this, we use the contains() method, which is a method of the classList object. Therefore, the class we want to check is passed as a parameter to the "contains()" method, which checks the certainty of the class.
<!DOCTYPE html> <html lang="en"> <head> <title>Check for specified class in a given element</title> <style> body{ background-color: #0a0a0a; color: white; } </style> </head> <body> <p id="para" class="my-para first lorems">I am para with certain classes, check now.</p> <button onclick="check()" style="margin-bottom: 8px;">Check Now</button><br> <div id="output" style="display: inline-block; padding: 0.3rem;"></div> <script> check = () => { var ptag = document.getElementById("para"); var cl = ptag.classList; var clContain = cl.contains("my-para"); if (clContain) { document.getElementById("output").innerHTML += "Element contains specified class"; document.getElementById("output").style.background = "green"; document.getElementById("output").style.color = "white"; } else { document.getElementById("output").innerHTML += "Element does not contains the specified class"; document.getElementById("output").style.background = "tomato"; document.getElementById("output").style.color = "white"; } } </script> </body> </html>
The output of the above example, because the output of "Elements contains specified class" is true.
Example 2: When the element does not contain the specified class
The following image shows "Element does not contain the specified class", which means that when classList.contains() is checked, it must have returned false. Therefore the error condition has terminated.
<!DOCTYPE html> <html lang="en"> <head> <title>Check for pecified class in a given element</title> <style> body{ background-color: #0a0a0a; color: white; } </style> </head> <body> <p id="para" class="my-para first lorems">I am para with certain classes, check now.</p> <button onclick="check()" style="margin-bottom: 8px;">Check Now</button><br> <div id="output" style="display: inline-block; padding: 0.3rem;"></div> <script> check = () => { var ptag = document.getElementById("para"); var cl = ptag.classList; var clContain = cl.contains("mypara"); if (clContain) { document.getElementById("output").innerHTML += "Element contains specified class"; document.getElementById("output").style.background = "green"; document.getElementById("output").style.color = "white"; } else { document.getElementById("output").innerHTML += "Element does not contains the specified class"; document.getElementById("output").style.background = "tomato"; document.getElementById("output").style.color = "white"; } } </script> </body> </html>
in conclusion
The return type of classList is DOMTokenList, which is an array type. It contains the list of classes present in that particular element. The DOMTokenList can be viewed by iterating it using any for loop or map.
var ptag = document.getElementById("para").classList; ptag.forEach(element => { console.log(element); });
The "contains()" method returns a Boolean result, which is true or false. The classList object contains an array of classes. So when the contains() method checks the specified class, it checks the DOMTokenList and makes a decision on its behalf and returns true or false.
The above is the detailed content of How to check if a given element has a specified class in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...
