简体   繁体   中英

Verify if certain divs contains a specific class

In my project there are 10 divs with the class.content like this:

<div class="content">Example</div>

I have already wroted a function that will atribute an.active class to my divs and they will appear like this:

<div class="content active">Example</div>

Now i need a function than will verify if all my divs with the class.content have the class.active too.

Thank you.

you can get the list of div and check

var contentDivs = document.getElementsByClassName("content")
for (var i = 0; i < contentDivs.length; i++) {
  var div = contentDivs[i];
  if (div.classList.contains("active")) {
    // do something 
  } else {
    // do something
  }
}

 document.querySelectorAll(".content").forEach(e => { console.log(e.classList.contains("active")); });
 <div class="content active">Example</div> <div class="content">Example</div> <div class="content active">Example</div> <div class="content">Example</div> <div class="content active">Example</div>

Here is an example.

Pass the elements to check in the following function:

function verify(elementX, nameOfStyleToCheck) {
  return elementX.classList.contains(nameOfStyleToCheck);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM