在JavaScript中使用多个条件的"querySelectorAll()"。

221

是否可以使用多个不相关的条件通过querySelectorAll()进行搜索?如果可以,如何实现?以及如何指定这些条件是AND还是OR?

例如:

如何在单个querySelectorAll()调用中查找所有formplegend?可能吗?


我不确定你所说的“AND或OR条件”是什么意思。你能举个例子吗? - Bergi
5
文档在第一个示例中涵盖了这一点。 - Andy
6个回答

334

使用多个不相关条件进行搜索是否可能通过querySelectorAll实现?

是的,因为querySelectorAll接受完整的CSS选择器,并且CSS具有选择器组的概念,它允许您指定多个不相关的选择器。例如:

var list = document.querySelectorAll("form, p, legend");

...将返回一个包含任何元素的列表,这些元素是 form或者 p或者 legend

CSS 还有另一个概念:基于更多条件进行限制。您只需组合选择器的多个方面即可。例如:

var list = document.querySelectorAll("div.foo");

...将返回所有具有类名为foo

元素列表,同时还忽略其他
元素。

当然,您也可以将它们组合使用:

var list = document.querySelectorAll("div.foo, p.bar, div legend");

这意味着“包括任何具有foo类的div元素,任何具有bar类的p元素以及任何在div内的legend元素。”


有没有可能使用 document.querySelectorAll 的单个类,例如我有 var hotspots = document.querySelectorAll(".clickMapItem.text , .clickMapItem.multiImageText"); var i; for (i = 0; i < hotspots.length; i++) { hotspots[i].style.display = "none"; } 我需要使用 if else 语句,如何检查它是否是 class display none 或其他内容。if (hotspots[0或1].style.display == "none") 不起作用。 - Mile Mijatović
2
@MileMijatovic:问题应该以问题的形式发布,而不是评论。但请参见:https://dev59.com/KILba4cB1Zd3GeqPdV25#25238247 - T.J. Crowder
好的,但一般来说,我所问的是否有可能做到?这个链接没有帮助。 - Mile Mijatović
选择器组的概念在2018年仍然对我有用...感谢分享。 - Eric Hepperle - CodeSlayer2010
年复一年,我仍然使用 document.querySelectorAll("div.foo", "div.bar"),但它从未起作用。代码用户体验是下一个用户体验 ;) - Gabriel Glenn
@GabrielGlenn,确实不起作用。请使用以下方法:document.querySelectorAll("div.foo, div.bar") …它会起作用。你的方法只能得到第一个项目“div.foo”,但不能得到第二个。为了使其工作,你需要删除中间的双引号,只保留第一个和最后一个引号… - willy wonka

36
根据文档,就像任何CSS选择器一样,您可以指定任意多个条件,并将它们视为逻辑“或”关系。

此示例返回文档中具有“note”或“alert”类的所有div元素的列表:

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

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

同时,要获取“AND”功能,你可以例如简单地使用多属性选择器,就像jQuery所说的那样:

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

例如,"input[id][name$='man']"指定了元素的id和name,必须同时满足这两个条件。对于类而言,".class1.class2"则表示需要有两个类名的元素。

所有可能的组合都是有效的,因此您可以轻松获得更复杂的“OR”和“AND”表达式的等效形式。


2
虽然该方法本身是正确的,但没有必要引用jQuery来解释CSS(特别是因为OP的问题仅限于JavaScript)。 - Chaya Cooper
也许这不会有什么坏处 :) 对于那些不经常使用CSS的人来说,这是找出更多选项的快速方法。 - mikus

10

使用纯JavaScript,您可以像SQL一样完成任何操作,包括您需要的所有操作:

<html>

<body>

<input type='button' value='F3' class="c2" id="btn_1">
<input type='button' value='F3' class="c3" id="btn_2">
<input type='button' value='F1' class="c2" id="btn_3">

<input type='submit' value='F2' class="c1" id="btn_4">
<input type='submit' value='F1' class="c3" id="btn_5">
<input type='submit' value='F2' class="c1" id="btn_6">

<br/>
<br/>

<button onclick="myFunction()">Try it</button>

<script>
    function myFunction() 
    {
        var arrFiltered = document.querySelectorAll('input[value=F2][type=submit][class=c1]');

            arrFiltered.forEach(function (el)
            {                
                var node = document.createElement("p");
                
                node.innerHTML = el.getAttribute('id');

                window.document.body.appendChild(node);
            });
        }
    </script>

</body>

</html>


1
这并没有真正回答问题,特别是“如何指定这些是AND还是OR条件”的部分,请参考已接受的答案。 - Meidan Alon

6

仅使用document.querySelectorAll('selector1, selector2, selector3')无法达到预期结果,需要同时使用forEach()方法才能实现目标。

document.querySelectorAll('selector1, selector2, selector3').forEach(item => {
        item.//code
    })

document.querySelectorAll('#id1, #id2, #id3').style = 'background-color: red';
document.querySelectorAll('#id4, #id5, #id6').forEach(item => {
    item.style = 'background-color: red';
})
<div id="id1">id1</div>
<div id="id2">id2</div>
<div id="id3">id3</div>
<div id="id4">id4</div>
<div id="id5">id5</div>
<div id="id6">id6</div>


4

使用querySelectorAll()

  • 逻辑与(&&)可以通过不使用逗号指定元素和属性来实现。
  • 逻辑或(||)可以通过使用逗号指定元素和属性来实现。

例如,下面显示了2个表单:

<form class="form1" method="post">
  <input type="text" id="input1" name="fruits" value="Apple">
  <p id="p1">Orange</p>
</form>
<form class="form2" method="post">
  <input type="text" id="input2" name="fruits" value="Banana">
  <p id="p2">Kiwi</p>
</form>

<逻辑与(&&)>

然后,您可以使用[name="fruits"]选择下面所示的苹果的<input>香蕉的<input>

document.querySelectorAll('[name="fruits"]');
// Apple's <input> and Banana's <input>

现在,通过不使用逗号指定元素和属性,您可以像下面所示一样仅选择Apple的<input>
                        // ↓ ↓ ↓ ↓ ↓  ↓ ↓ ↓               ↓ ↓ ↓ ↓ ↓ ↓ ↓     
document.querySelectorAll('form.form1 input[name="fruits"][id="input1"]');
// Apple's <input>

此外,您可以将.form1替换为[class="form1"],将[id="input1"]替换为#input1,如下所示:
                        //         .form1                       [id="input1"]
                        //     ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓                     ↓ ↓ ↓ ↓
document.querySelectorAll('form[class="form1"] input[name="fruits"]#input1');
// Apple's <input>

逻辑或(||)

接下来,您可以像下面展示的那样使用#input1选择苹果的<input>

document.querySelectorAll('#input1');
// Apple's <input>

现在通过使用逗号指定元素和属性,您可以选择以下所示的苹果的<input>橘子的<p>香蕉的<input>猕猴桃的<p>
                        //          ↓ ↓ ↓ ↓  ↓     
document.querySelectorAll('#input1, #input2, p');
                        //        ↑        ↑
// Apple's <input>, Orange's <p>, Banana's <input> and Kiwi's <p>

<逻辑与(&&)>和<逻辑或(||)>

此外,当然您可以像下面展示的一样同时使用逻辑与逻辑或

document.querySelectorAll('input#input1, input#input2, p#p1')[
// Apple's <input>, Orange's <p> and Banana's <input> 

4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接