javascript - 为什么 jQuery 类选择器只返回一个元素?

标签 javascript jquery jquery-selectors

文档中有多个带有该类的 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)}

引用:console expressions

关于javascript - 为什么 jQuery 类选择器只返回一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44769950/

相关文章:

javascript - 大 React 类还是外部 Controller ?

javascript - 无法动态添加要选择的选项

jquery mobile选择填充剩余空间

jquery - 如何在 jQuery 选择器中使用变量?

javascript - 如何过滤存储在 jQuery 变量中的数据

javascript - 如何在不重新加载页面的情况下使用 GET 发送变量

javascript - Bootstrap 4 多选下拉菜单

javascript - 第一次成功提交后提交停止工作

javascript - 为什么 *[checked] 不匹配单个选中的输入框?

javascript - For Loop 没有正确应用第 n 个 child