search
HomeWeb Front-endJS TutorialDetailed explanation of JQuery element operations

Detailed explanation of JQuery element operations

Apr 27, 2018 pm 01:47 PM
jqueryelementDetailed explanation

This time I will bring you a detailed explanation of the JQuery element operation. What are the precautions for JQuery element operation? The following is a practical case, let's take a look.

Step one: sizzle selector

"Find" (or select) based on the element's id, class, type, attribute, attribute value, etc.

HTML Element is simply based on css selector , in addition to some specific selectors.

Step 2: Query ancestors

parent()

Returns the direct parent element of the selected element. This method will only go up one level. DOM tree traversal

parents()

Optional parameters can be used to filter the search for parent elements

Returns all ancestor elements of the selected element, all the way up to the root of the document Element

parentsUntil()

Returns all ancestor elements between two given elements. The following is an example:

$(document).ready(function(){
  //会返回span开始到p为止的祖先元素
  $("span").parentsUntil("p");
});

Step 3: Query Descendants

children()

You can use optional parameters to filter the search for child elements

Returns all direct child elements of the selected element. This method only The DOM tree will be traversed to the next level

find()

You can use optional parameters to filter the search for elements

Returns the descendant elements of the selected element. All the way down to the last descendant

Step 4: Query siblings

siblings()

Return all sibling elements of the selected element

next()

Returns the next sibling element of the selected element

nextAll()

Returns all sibling elements after the selected element

nextUntil()

Returns all following sibling elements between the two given arguments

$(document).ready(function(){
  //返回介于 <h2>与<h6>元素之间的所有同胞元素
  $("h2").nextUntil("h6");
});</h6>
</h2>
prev(), prevAll() and prevUntil()

The prev(), prevAll() and prevUntil() methods work similarly to the above methods, except in the opposite direction: they return the previous sibling elements (traversing along the previous sibling elements in the DOM tree, and Not after element traversal).

Step 5: Add filtering when querying

first()

Return the first element among the selected elements

last()

Returns the last element among the selected elements

eq()

Returns the element with the specified index number among the selected elements. This is easy to understand. , an example is: $(element[flag]) has the same result as element.eq(flag)

filter()

Filters the query results, similar to not() below, but has the opposite effect

not()

Return all elements that do not match the standard

$(document).ready(function(){
  //返回不带有类名"target"的所有p元素
  $("p").not(".target");
});
After the element is found, we then need to operate on the found node according to the requirements.

Step 6: text(), html(), val() and attr()

text(), html(), val() and attr (), has

callback function. The callback function takes two parameters: the index of the current element in the selected element list, and the original (old) value. Then return the string you wish to use as the function's new value

1.text() - Sets or returns the text content of the selected element

2.html() - Set or return the content of the selected element (including HTML tags)

3.val() - Set or return the value of the form field

4.attr() - Set or return the attribute value

$("#btn1").click(function(){
  $("#test1").text(function(i,origText){
    return "旧文本: " + origText + " 新文本: index: " + i;
  });
});

Step 7: Add elements

append() - Insert content at the end of the selected element

prepend() - After the selected element Insert content at the beginning of the selected element

after() - Insert content after the selected element

before() - Insert content before the selected element

Step 8: Delete element

remove()可接受一个参数,允许你对被删元素进行过滤,empty()不可以

remove() - 删除被选元素(及其子元素)

empty() - 从被选元素中删除子元素

//等同于$("p.target").remove();
$("p").remove(".target");

第九步:替换元素

replaceAll()和replaceWith()功能类似,但是目标和源相反

replaceWith() - 用提供的内容替换集合中所有匹配的元素并且返回被删除元素的集合

replaceAll() - 用集合的匹配元素替换每个目标元素

第十步:class操作

addClass() - 向被选元素添加一个或多个类

removeClass() - 从被选元素删除一个或多个类

toggleClass() - 对被选元素进行添加/删除类的切换操作

hasClass() - 判断一个元素是否存在该class

第十一步:css()方法

设置或返回被选元素的一个或多个样式属性

css("propertyname"); - 返回propertyname属性的值

css("propertyname","value"); - 设置propertyname属性的值

css({"propertyname":"value","propertyname":"value",...}); - 设置多个值

第十二步:元素尺寸

width() 方法设置或返回元素的宽度(不包括内边距、边框或外边距

height() 方法设置或返回元素的高度(不包括内边距、边框或外边距)

innerWidth() 方法返回元素的宽度(包括内边距)

innerHeight() 方法返回元素的高度(包括内边距)

outerWidth() 方法返回元素的宽度(包括内边距和边框)

outerHeight() 方法返回元素的高度(包括内边距和边框)

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

源生js实现哈夫曼编码步骤详解

Vue实现不刷新分页

The above is the detailed content of Detailed explanation of JQuery element operations. 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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

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.

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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)