关于带有多个选择器的querySelector()

mau*_*oc8 4 html javascript dom selector

我有一种情况,我想要关注一个输入标签,如果它存在,或者它是容器,如果它没有.所以我想到了一种聪明的方式:

document.querySelector('.container input, .container').focus();
Run Code Online (Sandbox Code Playgroud)

但有趣的是,querySelector总是会返回.container元素.

我开始调查并发现,无论放置不同选择器的顺序如何,querySelector总是返回相同的元素.

例如:

var elem1 = document.querySelector('p, div, pre');
var elem2 = document.querySelector('pre, div, p');

elem1 === elem2; // true
elem1.tagName;   // "P".
Run Code Online (Sandbox Code Playgroud)

我的问题是:这种行为的"原因"是什么以及"规则"(如果有的话)使P元素优先于DIV和PRE元素.

注意:在上面提到的情况下,我提出了一个不太优雅但功能性的解决方案:

(document.querySelector('.container input') ||
 document.querySelector('.container')       ).focus();
Run Code Online (Sandbox Code Playgroud)

Thi*_*mer 6

document.querySelector仅返回匹配的第一个元素,从标记中的第一个元素开始.正如在MDN上所写:

返回文档中的第一个元素(使用文档节点的深度优先预先遍历遍历|文档标记中的第一个元素,并按照子节点数量的顺序迭代顺序节点)与指定的选择器组匹配.

如果您希望所有元素都与查询匹配,请使用document.querySelectorAll(docs),即document.querySelectorAll('pre, div, p').这将返回匹配元素的数组.


Raj*_*amy 4

官方文件说,

返回文档中与指定选择器组匹配的第一个元素(使用文档节点的深度优先预序遍历|按文档标记中的第一个元素,并按子节点数量的顺序迭代顺序节点)。

所以这意味着,在第一种情况下.container是父元素,以便它首先匹配并返回。在第二种情况下,该段落应该是文档中的第一个元素,同时与其他元素pre和进行比较div。于是就被退回了。