Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu November 14, 2022 › #class #HowTo

Check if an element contains a class

To check if an element contains a class name in JavaScript, we may use the contains() method of the classList property.

element.classList.contains(class)

In this method, we pass the class name as a parameter. It returns true if the element contains the class name, otherwise it returns false.

For example we have a <div> element with two classes my-div and new.

<div class="my-div new">I am the div element.</div>

Now if we want to check if the div element contains the class name new, we will pass the class name new to the contains() method as a parameter.

let myDiv = document.querySelector('div');
    myDiv.classList.contains('new') // true
  1. In the above example, we have selected the <div> element using the querySelector() method and stored it in a variable myDiv.
  2. We have passed the class name new to the contains() method of the classList property of the div element.
    Since the div element contains the class name new, it returns true.

How to check if an element contains a class. #

In this example, we will check if an li element contains a class name list, we will change its text dynamically using JavaScript. For example, we have the following code.

<ol>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li class="list">Four</li>
  <li>Five</li>
</ol>

Now, we will select all of the li element using the querySelectorAll() method and store in a variable as a nodeList.

Example : check if an element contains a class. #
<ol>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li class="list">Four</li>
  <li>Five</li>
</ol>
<script>
  let myOl = document.querySelectorAll('ol li');
  myOl.forEach((l)=> {
    if(l.classList.contains('list')){
      l.innerHTML = "Class Found"
    }
  })
</script>
Try it Yourself »

Conclusion #

In this article, you have learned How to check if an element contains a class name using JavaScript contains() method.

save
listen
AI Answer
Write Your Answer
loading
back
View All