querySelectorAll with multiple conditions

前端 未结 4 721
无人共我
无人共我 2020-12-04 17:26

Is it possible to make a search by querySelectorAll using multiple unrelated conditions? If yes how? And how to specify whether those are AND or OR criteria?

For exa

4条回答
  •  自闭症患者
    2020-12-04 17:49

    According to the documentation, just like with any css selector, you can specify as many conditions as you want, and they are treated as logical 'OR'.

    This example returns a list of all div elements within the document with a class of either "note" or "alert":

    var matches = document.querySelectorAll("div.note, div.alert");
    

    source: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

    Meanwhile to get the 'AND' functionality you can for example simply use a multiattribute selector, as jquery says:

    https://api.jquery.com/multiple-attribute-selector/

    ex. "input[id][name$='man']" specifies both id and name of the element and both conditions must be met. For classes it's as obvious as ".class1.class2" to require object of 2 classes.

    All possible combinations of both are valid, so you can easily get equivalent of more sophisticated 'OR' and 'AND' expressions.

提交回复
热议问题