1

There is form-group class in different div. But some of them contains form-group success and some contains form-group error class.

The class success and error are added from JavaScript

I want to log any text in console if all those div finally have form-group success class.

I tried this

const formGroup = document.querySelectorAll('.form-group')

  formGroup.forEach((item) => {
    if (item.className === 'form-group success') {
      console.log('cool')
    }
  })

But it is logging even if single div contains form-group success class. I want to log only when all div having form-group class have form-group success

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Dibas Dauliya
  • 639
  • 5
  • 20
  • this might be helpful: https://stackoverflow.com/questions/5898656/check-if-an-element-contains-a-class-in-javascript – MrAleister Nov 19 '20 at 13:22
  • 1
    Does this answer your question? [How to check if ALL objects of specific class share another class as well?](https://stackoverflow.com/questions/56251354/how-to-check-if-all-objects-of-specific-class-share-another-class-as-well) – Heretic Monkey Nov 19 '20 at 13:30

1 Answers1

2

I would go another way. Rather than checking the 'success' class for all (form-group)s check if any form-group has an 'error' class or not. This way you don't need to loop over an extra array.

const formGroup = document.querySelectorAll('.form-group.error')

if(!formGroup.length) console.log('No error!!')
Dhruvi Makvana
  • 895
  • 5
  • 17