search
HomeWeb Front-endFront-end Q&AUnderstand jquery's basic operations on elements in ten minutes

This article brings you a summary of jquery’s common functions, including how to obtain, move, create and modify elements. I hope it will be helpful to everyone.

Understand jquery's basic operations on elements in ten minutes

Introduction to jQuery

jQuery is a class library for JS that provides certain functions in JS Encapsulation makes DOM operations simple, the code is concise and easy to use, and it supports chain writing and has good compatibility.

The design idea and main usage of jQuery is: select a web page element and then perform some operations on it.

The special thing about jQuery is that after using jQuery to obtain the corresponding elements, it does not return these corresponding elements. Instead, it returns jQuery objects (objects constructed by jQuery), and this object can operate on these corresponding elements. Elements.

The functions that jQuery can achieve can definitely be achieved by JS, but not necessarily vice versa.

Let window.jQuery = window.$, and abbreviate jQuery as $.

How to get elements with jQuery

Just put a selection expression into the constructor $(), and then get the selected element. The selection expression can be a CSS selector or a jQuery-specific expression.

// CSS选择器
$(document) // 选择整个文档对象
$('#xxxID') // 选择ID为xxx的元素
$('div.xxxClass') // 选择Class为xxx的元素
$('input[name=first]') // 选择类名属性为first的元素
// jQuery特有表达式
$('a:first') // 选择网页中第一个a元素
$('tr:odd') // 选择表格的奇数行
$('#myForm:input') // 选择表单中的input元素
$('div:visible') // 选择可见的div元素
$('div:gt(2)') // 选择所有的div元素,除了前三个
$('div:animated') // 选择当前处于动画状态的div元素

How jQuery creates elements

Just pass the new element directly into the jQuery constructor.

The new element created will not be automatically inserted into the page. We also need to explicitly specify the location where it is inserted into the page.

For example: Create a pair of

tags
$(function(){
let $h1 = $(&#39;<h1></h1>&#39;) // 创建元素h1
$(&#39;body&#39;).append($h1) // 将元素h1放入到body里(用append表示成为body的最后一个子元素)
}

Use div for example:

$(&#39;div&#39;).prepend(&#39;&#39;) // 给div添加一个大儿子(即添加到最前)
$(&#39;div&#39;).append(选择器/jQuery对象) // 给div添加一个小儿子(即添加到最后)
$(&#39;<h2 id="xxx">xxx</h2>&#39;).appendTo(选择器/jQuery对象) // 在选择器选中的元素的子元素里,将“xxx”添加到最后

How to move elements with jQuery

Method 1: Move the element directly

$(&#39;div&#39;).insertAfter($(&#39;p&#39;)) // 将元素div移动到元素p后面

Method 2: Move other elements so that the target function reaches the position we want

$(&#39;p&#39;).after($(&#39;div&#39;)) // 把元素p放到元素div前

These two methods The difference: the returned objects are different. The object returned by method one is div, and the object returned by method two is p.

Different ways of moving elements:

.insertAfter()和.after() // 在现存元素的外部,从后面插入元素
.insertBefore()和.before() // 在现存元素的外部,从前面插入元素
.appendTo()和.append() // 在现存元素的内部,从后面插入元素
.prependTo()和.prepend() // 在现存元素的内部,从前面插入元素

How jQuery modifies element attributes

Use attr() to modify element attributes and their content, attr is The abbreviation of attribute is the abbreviation of setAttribute&getAttribute in JS. Whether attr takes a value or assigns a value is determined by the parameters of the function.

For example:

$(&#39;img&#39;).attr(&#39;width&#39;,&#39;100px&#39;) // 为属性&#39;width&#39;赋值&#39;100px&#39;

Usage method:

$(selector).attr(attribute) // 返回被选元素的属性值
$(selector).attr(attribute.value) // 返回被选元素的属性&值
$(selector).attr(attribute,function(index,oldvalue)) // 用函数返回值设置被选元素的属性&值
$(selector).attr({attribute1:value,attribute2:value...}) // 为被选一个及以上的元素设置属性&值,可一次修改多个属性的属性值

Supplement: The third usage method above means: use the return value of the function to assign attribute values ​​to attributes. This function receives and uses the selector's index value and the current attribute value. For example:

$(&#39;button&#39;).click(function(){
    $(&#39;img&#39;).attr(&#39;width&#39;,function(n,v){
     return v-50;  // 点击按钮图片宽度减少50
    })
})

jQuery's chain operation

After selecting a web page element, perform a series of operations on it, and all operations can be connected together and Written in the form of a chain, this is jQuery's chain operation.

For example: $('div').find('h3').eq(2).html('Hello'); This line of code can be split as follows

$(&#39;div&#39;) // 找到div元素
  .find(&#39;h3&#39;) // 选择其中的h3元素
  .eq(2) // 选择第3个h3元素
  .html(&#39;Hello&#39;); // 将它的内容改为Hello

jQuery also provides the back operation .end(), which allows the operation results to go back one step.

$(&#39;div&#39;)
 .find(&#39;h3&#39;)
 .eq(2)
 .html(&#39;Hello&#39;)
 .end() // 退回到选中所有的h3元素的那一步
 .eq(0) // 选中第一个h3元素
 .html(&#39;World&#39;) // 将它的内容改为World

Recommended related video tutorials: jQuery video tutorial

The above is the detailed content of Understand jquery's basic operations on elements in ten minutes. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金. If there is any infringement, please contact admin@php.cn delete
The Benefits of React: Performance, Reusability, and MoreThe Benefits of React: Performance, Reusability, and MoreApr 15, 2025 am 12:05 AM

React’s popularity includes its performance optimization, component reuse and a rich ecosystem. 1. Performance optimization achieves efficient updates through virtual DOM and diffing mechanisms. 2. Component Reuse Reduces duplicate code by reusable components. 3. Rich ecosystem and one-way data flow enhance the development experience.

React: Creating Dynamic and Interactive User InterfacesReact: Creating Dynamic and Interactive User InterfacesApr 14, 2025 am 12:08 AM

React is the tool of choice for building dynamic and interactive user interfaces. 1) Componentization and JSX make UI splitting and reusing simple. 2) State management is implemented through the useState hook to trigger UI updates. 3) The event processing mechanism responds to user interaction and improves user experience.

React vs. Backend Frameworks: A ComparisonReact vs. Backend Frameworks: A ComparisonApr 13, 2025 am 12:06 AM

React is a front-end framework for building user interfaces; a back-end framework is used to build server-side applications. React provides componentized and efficient UI updates, and the backend framework provides a complete backend service solution. When choosing a technology stack, project requirements, team skills, and scalability should be considered.

HTML and React: The Relationship Between Markup and ComponentsHTML and React: The Relationship Between Markup and ComponentsApr 12, 2025 am 12:03 AM

The relationship between HTML and React is the core of front-end development, and they jointly build the user interface of modern web applications. 1) HTML defines the content structure and semantics, and React builds a dynamic interface through componentization. 2) React components use JSX syntax to embed HTML to achieve intelligent rendering. 3) Component life cycle manages HTML rendering and updates dynamically according to state and attributes. 4) Use components to optimize HTML structure and improve maintainability. 5) Performance optimization includes avoiding unnecessary rendering, using key attributes, and keeping the component single responsibility.

React and the Frontend: Building Interactive ExperiencesReact and the Frontend: Building Interactive ExperiencesApr 11, 2025 am 12:02 AM

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

React and the Frontend Stack: The Tools and TechnologiesReact and the Frontend Stack: The Tools and TechnologiesApr 10, 2025 am 09:34 AM

React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

React's Role in HTML: Enhancing User ExperienceReact's Role in HTML: Enhancing User ExperienceApr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

React Components: Creating Reusable Elements in HTMLReact Components: Creating Reusable Elements in HTMLApr 08, 2025 pm 05:53 PM

React components can be defined by functions or classes, encapsulating UI logic and accepting input data through props. 1) Define components: Use functions or classes to return React elements. 2) Rendering component: React calls render method or executes function component. 3) Multiplexing components: pass data through props to build a complex UI. The lifecycle approach of components allows logic to be executed at different stages, improving development efficiency and code maintainability.

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
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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.