Table of Contents
Overview
grammar
algorithm
Example 1: When the element contains the specified class
Example 2: When the element does not contain the specified class
in conclusion

" >in conclusion

Home Web Front-end JS Tutorial How to check if a given element has a specified class in JavaScript?

How to check if a given element has a specified class in JavaScript?

Sep 08, 2023 am 08:49 AM

如何在 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);
Copy after login
  • 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>
Copy after login

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>
Copy after login

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);
});
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

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...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

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.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

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 using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

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...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

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.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

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 Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

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.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

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. �...

See all articles