亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
What is the problem?
NodeList.js Support for array methods
push and unshift
concat
pop, shift, map, slice, filter,
getset and
call Method
item Method
owner Attributes
NodeList.js Compatibility
method or the expand operator. Here's how to do it:
Why does the jQuery selector return prevObject instead of a normal element?
How to loop through NodeList?
What is the use of the .prev() method in jQuery?
Is jQuery still relevant in 2022?
How to select a specific node from NodeList?
Can I use map, filter, and reduce methods on NodeList?
What is the difference between querySelector and querySelectorAll?
How to check if NodeList is empty?
Home Web Front-end JS Tutorial Lose the jQuery Bloat -

Lose the jQuery Bloat -

Feb 19, 2025 am 08:27 AM

Lose the jQuery Bloat -

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:

  1. jQuery contains many features that you don't need or use (and therefore it is unnecessary to be huge).
  2. jQuery takes on too many functions for too many people. Generally, smaller libraries can do some tasks better.
  3. In terms of DOM operations, the browser API can now perform most of the functions of jQuery.
  4. The browser API is now more synchronized, for example using addEventListener instead of attachEvent.

What is the problem?

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:

The

NodeList 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 不是函數(shù)
Therefore, you have to do the following:

var nodes = document.querySelectorAll('div');
for(var i = 0, l = nodes.length; i < l; i++) {
  // do something with nodes[i]
}
Or even only use "hack":

[].forEach.call(document.querySelectorAll('div'), function(node) {
    // do something
});
The browser's native NodeList has only one method:

. 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
This is where NodeList.js comes in - making it as easy to operate a DOM using a browser native API as using jQuery, but only requires 4k compression size.

Solution

I created NodeList.js because I've been using native DOM APIs, but want to make them more concise, thus reducing a lot of redundancy when writing code (such as for loops).

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:

Selecting a DOM node is simple:

// Return to my NodeList$$(selector);

This method is used in the background

. querySelectorAll(selector)

But how does it compare to jQuery?

Glad you asked this question. Let's compare native JS, jQuery, and NodeList.js.

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

If we want a method chain (similar to jQuery), we do the following, which returns a reference to NodeList:

$$('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');
  // 或?qū)?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 不是函數(shù)

NodeList.js Support for array methods

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 popshift 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

, the latter always pops up or shifts an element in the array regardless of what is passed as a parameter.

map If each mapped value is a node, the

method returns a NodeList; if not, it returns an array of mapped values.

The slicefilter and

methods do the same as they do in real arrays, but return a NodeList.

Array.prototype Since NodeList.js does not inherit directly from Array.prototype, if you add a method to

when loading NodeList.js, it will not be inherited.

You can view the remaining array methods of NodeList.js here.

Special Method

ownerNodeList.js has four unique methods, and a property called prevObject, which is equivalent to the

attribute of jQuery.

getset and

Method:

hrefSome 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

method to access these properties:
var nodes = document.querySelectorAll('div');
nodes.forEach(function(node) {
  // do something
});
// 錯誤:nodes.forEach 不是函數(shù)
The

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

The

call method allows you to call element-specific methods (for example, pause on a video element):

$('button').text('Click Me');

item Method

The

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

The

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.

NodeList.js Compatibility

My library is compatible with all major new browsers as described below.

BrowserversionFireFox6 Safari5.0.5 Chrome6 IE9 Opera11.6 Conclusion

Now we can finally use the useful NodeList object!

For a compression size of about 4k you get all the above and more, which you can learn about in the GitHub repository of NodeList.js.

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?

NodeList and HTMLCollection are both node collections. The main difference between them is that NodeList can contain any node type, while HTMLCollection is a collection of element nodes. HTMLCollection is also dynamic, meaning it will be updated automatically when the document structure changes. NodeList, on the other hand, is static and does not update to reflect changes in the document.

How to convert NodeList to an array?

You can convert NodeList to an array using the

method or the expand operator. Here's how to do it:

var nodes = document.querySelectorAll('div');
nodes.forEach(function(node) {
  // do something
});
// 錯誤:nodes.forEach 不是函數(shù)

Why does the jQuery selector return prevObject instead of a normal element?

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.

How to loop through NodeList?

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]
}

What is the use of the .prev() method in jQuery?

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.

Is jQuery still relevant in 2022?

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.

How to select a specific node from NodeList?

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

Can I use map, filter, and reduce methods on NodeList?

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.

What is the difference between querySelector and querySelectorAll?

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.

How to check if NodeList is empty?

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
How to make an HTTP request in Node.js? How to make an HTTP request in Node.js? Jul 13, 2025 am 02:18 AM

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

React vs Angular vs Vue: which js framework is best? React vs Angular vs Vue: which js framework is best? Jul 05, 2025 am 02:24 AM

Which JavaScript framework is the best choice? The answer is to choose the most suitable one according to your needs. 1.React is flexible and free, suitable for medium and large projects that require high customization and team architecture capabilities; 2. Angular provides complete solutions, suitable for enterprise-level applications and long-term maintenance; 3. Vue is easy to use, suitable for small and medium-sized projects or rapid development. In addition, whether there is an existing technology stack, team size, project life cycle and whether SSR is needed are also important factors in choosing a framework. In short, there is no absolutely the best framework, the best choice is the one that suits your needs.

JavaScript time object, someone builds an eactexe, faster website on Google Chrome, etc. JavaScript time object, someone builds an eactexe, faster website on Google Chrome, etc. Jul 08, 2025 pm 02:27 PM

Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

Handling Promises: Chaining, Error Handling, and Promise Combinators in JavaScript Handling Promises: Chaining, Error Handling, and Promise Combinators in JavaScript Jul 08, 2025 am 02:40 AM

Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)

What is the cache API and how is it used with Service Workers? What is the cache API and how is it used with Service Workers? Jul 08, 2025 am 02:43 AM

CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.

Leveraging Array.prototype Methods for Data Manipulation in JavaScript Leveraging Array.prototype Methods for Data Manipulation in JavaScript Jul 06, 2025 am 02:36 AM

JavaScript array built-in methods such as .map(), .filter() and .reduce() can simplify data processing; 1) .map() is used to convert elements one to one to generate new arrays; 2) .filter() is used to filter elements by condition; 3) .reduce() is used to aggregate data as a single value; misuse should be avoided when used, resulting in side effects or performance problems.

JS roundup: a deep dive into the JavaScript event loop JS roundup: a deep dive into the JavaScript event loop Jul 08, 2025 am 02:24 AM

JavaScript's event loop manages asynchronous operations by coordinating call stacks, WebAPIs, and task queues. 1. The call stack executes synchronous code, and when encountering asynchronous tasks, it is handed over to WebAPI for processing; 2. After the WebAPI completes the task in the background, it puts the callback into the corresponding queue (macro task or micro task); 3. The event loop checks whether the call stack is empty. If it is empty, the callback is taken out from the queue and pushed into the call stack for execution; 4. Micro tasks (such as Promise.then) take precedence over macro tasks (such as setTimeout); 5. Understanding the event loop helps to avoid blocking the main thread and optimize the code execution order.

See all articles