问题
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