0

I'd like to run an IF statement whereby it runs if any one of a series of specific class names exist on the page somewhere. I currently have this method, but when the script runs, it only pays attention to the first class name in the list and then ignores the rest.

if (document.querySelector('.class_a'||'.class_b'||'.class_c')) { // do stuff }

Any ideas on how I can execute this fairly simple command please?

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
Chuwa Feet
  • 49
  • 5
  • 1
    Does this answer your question? [querySelectorAll with multiple conditions](https://stackoverflow.com/questions/34001917/queryselectorall-with-multiple-conditions) – Ruben Helsloot Jun 14 '21 at 14:55
  • Thank you - I tried it though, and it always returns true, even if the elements don't exist on the page :( – Chuwa Feet Jun 14 '21 at 16:09

2 Answers2

1

The , is what you want to use to group selectors so

if (document.querySelector('.class_a, .class_b, .class_c')) {
 // do stuff 
}
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
  • I tried this and it only returns true if the first element exists (.class_a), ignoring the rest. – Chuwa Feet Jun 14 '21 at 16:10
  • @ChuwaFeet this selector combined with `querySelector` will select only the first one, of all the classes, in the DOM it finds. Do you want to select more than the first found element ? Do you care which elements exist or only care to know if any of them exist in the DOM ? – Gabriele Petrioli Jun 14 '21 at 20:02
  • Hi Gabriele, yes that's correct - I don't need all of the elements to be true in the list, however i need the function to run if any one or more of the elements exists. ie if .class_a isn't in the DOM, then I want the script to fire if .class_b exists instead. – Chuwa Feet Jun 15 '21 at 10:07
  • @ChuwaFeet then this code should do that. Are those elements added dynamically ? If so you would need to run the code **after** adding them to the DOM. – Gabriele Petrioli Jun 15 '21 at 11:13
  • Thank you - you're right. Seems like it was an issue with the timing of when the scripts were firing. Many thanks my man. Do you have paypal? I'd like to buy you a drink. – Chuwa Feet Jun 15 '21 at 12:43
  • @ChuwaFeet lol, that is alright :) I am glad i could help. You can accept the answer though. – Gabriele Petrioli Jun 15 '21 at 13:09
0

You need to change the selector, separating with "," character.


if (document.querySelector('.class_a, .class_b, .class_c')) { // do stuff }