search
HomeWeb Front-endJS TutorialHow to search and operate JQuery elements

This time I will show you how to search and operate JQuery elements, and what are the precautions for searching and operating JQuery elements. 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中文网其它相关文章!

推荐阅读:

如何使用jquery layui弹出层

怎样使用JS调用模式与this关键字绑定

The above is the detailed content of How to search and operate JQuery elements. 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 Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

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 Article

Hot 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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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.