简体   繁体   中英

Is there a way in Javascript to select elements matching a boolean expression of multiple class names?

Say I have multiple elements on a page and each element has one or more class names, eg:

<div class="A1 A2 B1">…</div>
<div class="A2 C3">…</div>
<div class="B2 C3">…</div>
etc.

Is there a way to select, for example, all elements that have

class = (A1 OR A2) AND (B1 OR B2) 

?

You could use css selectors with the querySelectorAll function.

(A1 OR A2) AND (B1 OR B2) is the same as saying (A1 AND B1) OR (A1 AND B2) OR (A2 AND B1) OR (A2 AND B2) which we can express using css selectors like this .A1.B1, .A1.B2, .A2.B1, .A2.B2 .

 // (A1 OR A2) AND (B1 OR B2) const selector = '.A1.B1, .A1.B2, .A2.B1, .A2.B2'; const $elems = document.querySelectorAll(selector); $elems.forEach($el => console.log($el));
 <div class="A1 A2 B1"></div> <div class="A1 B1"></div> <div class="A1 B2"></div> <div class="A2 B1"></div> <div class="A2 B2"></div> <div class="A2 C3"></div> <div class="B2 C3"></div>

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