Core points
NodeList.js, as an alternative to DOM operation for jQuery, offers similar functionality, but is smaller (4k after compression) and takes advantage of improvements to the native browser API.
Unlike jQuery, NodeList.js treats node arrays as single nodes, enabling cleaner code and easier NodeList object operations.
NodeList.js contains special methods for setting and getting attributes, calling element-specific methods, and accessing nodes in NodeList, and the prevObject
attribute equivalent to jQuery's owner
attribute.
NodeList.js is compatible with mainstream browsers after a specific version (Firefox 6, Safari 5.0.5, Chrome 6, IE 9, Opera 11.6), and is automatically updated to include new methods/properties added by the browser.
p.tip { background-color: rgba(128,128,128,0.05); border-top-right-radius: 5px; border-bottom-right-radius: 5px; padding: 15px 20px; border-left: 10px solid rgba(128,128,128,0.075); }
In recent years, jQuery has become the de facto JavaScript library on the Web. It removes a lot of cross-browser inconsistencies and adds a layer of popular syntactic sugar to client scripts. One of its main pain points in abstraction processing is DOM operations, but since the advent of jQuery, native browser APIs have been significantly improved, and the concept of "you probably don't need jQuery" has become popular.
The reasons are as follows:
addEventListener
instead of attachEvent
. The problem is that using native (or pure) JavaScript for DOM can be troublesome compared to jQuery. This is because you have to write more redundant code and handle the browser's useless NodeList.
First, let's take a look at MDN's definition of NodeList:
TheNodeList object is a collection of nodes, such as those returned by the Node.childNodes
and document.querySelectorAll
methods.
There are sometimes dynamics NodeList (which can be confusing):
In some cases, NodeList is a dynamic collection, which means changes in the DOM are reflected in the collection. For example, Node.childNodes
is dynamic.
This can be a problem because you can't tell which are dynamic and which are static. Unless you remove each node from the NodeList and then check if the NodeList is empty. If empty, you have a dynamic NodeList (it's just a bad idea).
In addition, the browser does not provide any useful methods to manipulate these NodeList objects.
For example, unfortunately, it is not possible to loop through nodes using forEach
var nodes = document.querySelectorAll('div'); nodes.forEach(function(node) { // do something }); // 错误:nodes.forEach 不是函数
var nodes = document.querySelectorAll('div'); for(var i = 0, l = nodes.length; i < l; i++) { // do something with nodes[i] }
[].forEach.call(document.querySelectorAll('div'), function(node) { // do something });
. It returns a node from NodeList via index. When we can access the node like we use an array (using item
), it is completely useless: array[index]
var nodes = document.querySelectorAll('div'); nodes.item(0) === nodes[0]; // true
Solution
NodeList.js is a wrapper for the native DOM API that allows you to manipulate arrays of nodes (i.e. my NodeList) as if it were a single node. This gives you more functionality than the browser native NodeList object.
If you think this is good, get a copy of NodeList.js from the official GitHub repository and continue reading the rest of this tutorial.
Usage:
// Return to my NodeList
$$(selector);
This method is used in the background
. querySelectorAll(selector)
Suppose we have three buttons:
Let's change the text of each button to "Click Me":
Native JS:
var buttons = document.querySelectorAll('button'); // 返回浏览器无用的 NodeList for(var i = 0, l = buttons.length; i < l; i++) { buttons[i].textContent = 'Click Me'; }
jQuery:
$('button').text('Click Me');
NodeList.js:
$$('button').textContent = 'Click Me';
Here, we see that NodeList.js can effectively treat NodeList as a single node. That is, we reference a NodeList and set its
property to "Click Me". NodeList.js then performs this for each node in the NodeList. Very clever, right? textContent
$$('button').set('textContent', 'Click Me');
Now, let's add a click event listener to each button:
Native JS:
var buttons = document.querySelectorAll('button'); // 返回浏览器无用的 NodeList for(var i = 0, l = buttons.length; i < l; i++) { buttons[i].addEventListener('click', function() { this.classList.add('clicked'); }); }
jQuery:
$('button').on('click', function() { $(this).addClass('click'); // 或将 jQuery 与原生混合使用 `classList`: this.classList.add('clicked'); });
NodeList.js:
$$('button').addEventListener('click', function() { this.classList.add('clicked'); });
Okay, so the
method of jQuery is quite good. My library uses the browser's native DOM API (hence on
), but that doesn't prevent us from creating an alias for the method: addEventListener
$$.NL.on = $$.NL.addEventListener; $$('button').on('click', function() { this.classList.add('clicked'); });
Not bad! This demonstrates how we add our own method:
var nodes = document.querySelectorAll('div'); nodes.forEach(function(node) { // do something }); // 错误:nodes.forEach 不是函数
NodeList.js does inherit from Array.prototype
, but not directly, because some methods have been changed, so it makes sense to use them with NodeList (array of nodes).
push
and unshift
For example: push
and unshift
methods can only take nodes as parameters, otherwise an error will be thrown:
var nodes = document.querySelectorAll('div'); for(var i = 0, l = nodes.length; i < l; i++) { // do something with nodes[i] }
So both push
and unshift
return NodeList to allow method chaining, meaning it is different from JavaScript's native Array#push
or Array#unshift
methods, which accept anything and return the array's New length. If we do want the length of NodeList, we just need to use the length
property.
These two methods, like JavaScript's native array method, change the NodeList.
concat
concat
The method accepts the following as parameters:
[].forEach.call(document.querySelectorAll('div'), function(node) { // do something });
concat
is a recursive method, so these arrays can be as deep as we would like to be and will be flattened. However, if any element in the passed array is not a node, NodeList, or HTMLCollection, it will throw an error.
concat
Returns a new NodeList, just like the Array#concat
method of javascript.
pop
, shift
, map
, slice
, filter
,
Both the pop
shift
and Array#pop
methods can take optional parameters, indicating how many nodes to pop or shift from the NodeList. Unlike JavaScript's native Array#shift
or
map
If each mapped value is a node, the
The slice
filter
and
Array.prototype
Since NodeList.js does not inherit directly from Array.prototype
, if you add a method to
You can view the remaining array methods of NodeList.js here.
owner
NodeList.js has four unique methods, and a property called prevObject
, which is equivalent to the
get
set
and
href
Some elements have attributes specific to elements of that type (for example, the $$('a').href
attribute on the anchor tag). This is why get
will return undefined - because it is not a property inherited by every element in NodeList. This is how we use the
var nodes = document.querySelectorAll('div'); nodes.forEach(function(node) { // do something }); // 错误:nodes.forEach 不是函数
set
method can be used to set these properties for each element:
var nodes = document.querySelectorAll('div'); for(var i = 0, l = nodes.length; i < l; i++) { // do something with nodes[i] }
set
also returns NodeList to allow method chaining. We can use it in textContent
etc. (both equivalent):
[].forEach.call(document.querySelectorAll('div'), function(node) { // do something });
We can also set multiple properties in one call:
var nodes = document.querySelectorAll('div'); nodes.item(0) === nodes[0]; // true
All the above operations can be done using any attribute, for example style
:
var buttons = document.querySelectorAll('button'); // 返回浏览器无用的 NodeList for(var i = 0, l = buttons.length; i < l; i++) { buttons[i].textContent = 'Click Me'; }
call
Method call
method allows you to call element-specific methods (for example, pause
on a video element):
$('button').text('Click Me');
item
Method item
method is equivalent to the eq
method of jQuery. It returns a NodeList which contains only the nodes passing the index:
$$('button').textContent = 'Click Me';
owner
Attributes owner
attribute is equivalent to the prevObject
of jQuery.
$$('button').set('textContent', 'Click Me');
btns.style
returns a style array, while owner
will return the NodeList mapped by style
.
My library is compatible with all major new browsers as described below.
Browser version
Since NodeList.js uses a browser as a dependency, no upgrade is required. Whenever the browser adds new methods/attributes to the DOM element, you can use these methods/attributes automatically via NodeList.js. All of this means that the only deprecation you need to worry about is the browser removal method. These are usually very low usage methods because we can't break the web.
So what do you think? Would you consider using this library? Are any important features missing? I'd love to hear your comments in the comments below.
Frequently Asked Questions about DOM Operations with NodeList.js
What is the difference between NodeList and HTMLCollection?
You can convert NodeList to an array using the
var nodes = document.querySelectorAll('div'); nodes.forEach(function(node) { // do something }); // 错误:nodes.forEach 不是函数
jQuery's chaining mechanism works by storing previous objects before making changes. This allows you to use the .end()
method to restore to your previous state. If you want to get the actual DOM element, you can use the .get()
method or array notation.
You can loop through the NodeList using the for loop, for...of loop, or forEach()
method. Here is an example using a for loop:
var nodes = document.querySelectorAll('div'); for(var i = 0, l = nodes.length; i < l; i++) { // do something with nodes[i] }
The .prev()
method in jQuery is used to select the selected element immediately next to the previous sibling. If a selector is provided, the previous sibling element is retrieved only when the selector is matched.
While jQuery was a game-changer at launch, the modern JavaScript ecosystem has changed significantly. Many of the features that make jQuery popular are now built into JavaScript itself. However, jQuery is still widely used and maintained, and it may be a good choice for some projects.
You can select a specific node from NodeList using the array notation or the item()
method. Here's how to do it:
[].forEach.call(document.querySelectorAll('div'), function(node) { // do something });
NodeList is not an array, so it does not have methods like map, filter, and reduce. However, you can convert NodeList to an array and then use these methods.
querySelector
Returns the first element in the document that matches the specified CSS selector, and querySelectorAll
returns the NodeList of all elements that match the CSS selector.
You can check if NodeList is empty by checking its length
property. If the length is 0, NodeList is empty. Here's how to do it:
var nodes = document.querySelectorAll('div'); nodes.item(0) === nodes[0]; // true
The above is the detailed content of Lose the jQuery Bloat . For more information, please follow other related articles on the PHP Chinese website!