How can I emulate the jQuery $ selector in pure javascript? [closed]

梦想与她 提交于 2021-02-15 07:57:27

问题


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?

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


回答1:


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);
};

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

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.



来源:https://stackoverflow.com/questions/51409162/how-can-i-emulate-the-jquery-selector-in-pure-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!