如何在纯JavaScript中模拟jQuery $选择器? [英] How can I emulate the jQuery $ selector in pure javascript?

查看:52
本文介绍了如何在纯JavaScript中模拟jQuery $选择器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jQuery $选择器使获取DOM元素变得容易得多.我希望能够用普通的javascript复制此选择器.我该怎么办?

Using the jQuery $ selector makes getting DOM elements a lot easier. I want to be able to replicate this selector in plain javascript. How would I do this?

注意:我不想用 document.querySelector()替换代码中所有 $('')实例,而是要定义 $ 作为函数.

Note: I do not want to replace all instancew of $('')in my code with document.querySelector(), rather, I want to define $ as a function.

推荐答案

您正在寻找

You're looking for document.querySelectorAll(). You don't need to use the querySelectorAll method on document, it can be any DOM Element. If you want to use it in a style somewhat similar to jQuery, you can write a function that wraps it, like this:

var $ = function (selector) {
  return document.querySelectorAll(selector);
};

该示例假定您使用的是ES5或更旧版本,并且用较新版本的语言进行重写应该很简单.

That example assumes you're using ES5 or older, and rewriting it in newer versions of the language should be trivial.

请记住,这将返回 NodeList ,而不是您可能认为是的 Array ,所以这里没有很多方法.

Keep in mind that this will return a NodeList, not an Array you might think it does, so many methods from it won't be there.

这篇关于如何在纯JavaScript中模拟jQuery $选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆