search
HomeWeb Front-endJS TutorialNative JavaScript Equivalents of jQuery Methods: the DOM and Forms

Native JavaScript Equivalents of jQuery Methods: the DOM and Forms

Core points

  • jQuery is a useful tool for developers who need to support legacy Internet Explorer or write libraries like jQuery longer than developing applications. However, for most other cases, using native JavaScript is more efficient because it does not require loading large libraries like jQuery.
  • Native JavaScript equivalents of commonly used jQuery methods such as DOM selectors and DOM operations are usually executed faster and more efficiently than their jQuery counterparts. For example, using document.getElementsByClassName or document.getElementById may be much faster than using jQuery's $() wrapper.
  • HTML5 provides built-in support for a variety of common input types without adding additional JavaScript or jQuery code for form validation. Old browsers that do not support these new types will be restored to standard text input fields and require server-side verification.

About my recent "Do you really need jQuery? 》 article, the debate continues, but in short, there are two reasons to use jQuery: 1. You need to support IE6/7/8 (remember you can't migrate to jQuery 2.0), or 2. Without jQuery, you will spend more than development The application takes longer to write a library like jQuery.

Please be pragmatic for all other situations. jQuery is a 270KB universal library. It's unlikely that you need all the functionality it provides, even if you omit certain modules, it's still a big chunk of code. You may load a minified version of 30KB from the CDN, but the browser must stop processing and parse the code on each page before doing any other actions. This is the first in a series of articles that showcase native JavaScript equivalents to commonly used jQuery methods. While you may want to wrap some of these in shorter, similar aliased functions, you certainly don't need to create your own jQuery-like library.

DOM selector

jQuery allows DOM node selection using CSS selector syntax, for example:

// 在 ID 为“first”的文章中查找所有具有类“summary”的段落
var n = $("article#first p.summary");

Native equivalent:

var n = document.querySelectorAll("article#first p.summary");

document.querySelectorAll is implemented in all modern browsers and IE8 (although this only supports CSS2.1 selectors). jQuery provides additional support for more advanced selectors, but for the most part it runs within the $() wrapper. Native JavaScript also offers four alternatives, which are almost certainly faster than document.querySelectorAll if you can use them: querySelectorAll

  1. document.querySelector(selector) — Get only the first matching node
  2. document.getElementById(idname) — Get a single node by its ID name
  3. document.getElementsByTagName(tagname) — Get the node matching the element (such as h1, p, strong, etc.).
  4. document.getElementsByClassName(class) — Get a node with a specific class name
The

getElementsByTagName and getElementsByClassName methods can also be applied to a single node to limit the result to descendants only, for example:

// 在 ID 为“first”的文章中查找所有具有类“summary”的段落
var n = $("article#first p.summary");

Let's do some testing. I wrote some small scripts to get from my "Do you really need jQuery?" 》 Searches all comment nodes 10,000 times in the article. Results:

代码 时间
// jQuery 2.0<br>var c = $("#comments .comment"); 4,649 ms
// jQuery 2.0<br>var c = $(".comment"); 3,437 ms
// 原生 querySelectorAll<br>var c = document.querySelectorAll("#comments .comment"); 1,362 ms
// 原生 querySelectorAll<br>var c = document.querySelectorAll(".comment"); 1,168 ms
// 原生 getElementById / getElementsByClassName<br>var n = document.getElementById("comments");<br>var c = n.getElementsByClassName("comment"); 107 ms
// 原生 getElementsByClassName<br>var c = document.getElementsByClassName("comment"); 75 ms

I can't claim strict lab conditions, nor does it reflect real-world usage, but in this case native JavaScript is 60 times faster. It also states that getting nodes by ID, tag, or class is usually better than querySelectorAll.

DOM operation

jQuery provides several ways to add more to the DOM, such as:

// 在 ID 为“first”的文章中查找所有具有类“summary”的段落
var n = $("article#first p.summary");

Below the surface, jQuery uses the native innerHTML method, for example:

var n = document.querySelectorAll("article#first p.summary");

You can also use DOM build technology. These are safer, but rarely faster than innerHTML:

var n = document.getElementById("first");
var p = n.getElementsByTagName("p");

We can also delete all child nodes in jQuery:

$("#container").append("<p>more content</p>");

Native equivalents to use innerHTML:

document.getElementById("container").innerHTML += "<p>more content</p>";

or a small function:

var p = document.createElement("p");
p.appendChild(document.createTextNode("more content"));
document.getElementById("container").appendChild(p);

Finally, we can delete the entire element from the DOM in jQuery:

$("#container").empty();

or native JavaScript:

document.getElementById("container").innerHTML = null;

Scalable Vector Graphics (SVG)

Core jQuery library has been developed to process current documents. SVG also has DOM, but jQuery does not provide direct manipulation to these objects, as it usually requires methods such as createElementNS and getAttributeNS . It works and there are several plugins available, but it's more efficient to write your own code or use a dedicated SVG library like Raphaël or svg.js.

HTML5 Form

Even the most basic web applications will have one or two forms. You should always verify user data on the server side, but ideally you would supplement it with client verification so that the errors can be caught before submitting the form. Client verification is simple: 1. Run a function when the form is submitted. 2. If you encounter any problems, stop submitting and display an error.

You can use jQuery. You can use native JavaScript. Which one should you choose? Neither chooses . HTML5 supports a variety of commonly used input types, such as email, phone, URL, number, time, date, color, and custom fields based on regular expressions. For example, if you want to force a user to enter an email address, please use:

var c = document.getElementById("container");
while (c.lastChild) c.removeChild(c.lastChild);

Unless you need more complex features (such as comparing two or more fields or displaying custom error messages), there is no need for additional JavaScript or jQuery code. Older browsers (including IE9 and below) do not understand the new type and will be restored to standard text input fields. These users will fall back to server-side verification; this is not a great experience, but you can apply a shim or hope these people see the light and upgrade. In my next post, we will look at native CSS class operations and animations.

FAQs about jQuery and native JavaScript

(The FAQ part is omitted here because the content of this part is weakly related to the picture and article subject, and the article is longer, so it can be processed separately.)

The above is the detailed content of Native JavaScript Equivalents of jQuery Methods: the DOM and Forms. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor