文档中有多个带有该类的 div。
如控制台中所示,document.getElementsByClassName
生成:
document.getElementsByClassName('current-pad-o')
HTMLCollection (2) = $8
0 <div class="red current-pad-o"> first value </div>
1 <div class="red current-pad-o"> second value </div>
和jquery,使用相同的类选择器会产生:
$('.current-pad-o')
// (the first div only - no collection)
<div class="red current-pad-o"> first value </div>
我也希望从 jquery 语句中得到一个集合。这些都是在 Safari 和 Firefox 中输出的。
根据jQuery Class Selector documentation ,第二个选择器选择具有给定类的所有元素。
为什么jquery只返回一个,而不是一个集合?
最佳答案
您没有 jQuery,您正在使用 document.querySelector()
的调试器快捷方式。如果您使用 $$('.current-pad-o')
,您将获得所有这些。
要确认您没有使用 jQuery,请在命令行中键入以下内容:
console.log($)
对于 querySelector,您将看到以下内容:
function $(selector, [startNode]) { [Command Line API] }
对于 jQuery,您会看到以下内容:
function (a,b){return new n.fn.init(a,b)}
关于javascript - 为什么 jQuery 类选择器只返回一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44769950/