,*").find("li") is better than $(&qu"/> ,*").find("li") is better than $(&qu">
search
HomeWeb Front-endJS TutorialThe rephrased title is: Rarely Used jQuery Selectors

重新表述的标题为:Rarely Used jQuery Selectors

Selectors are crucial. Most jQuery methods require some sort of element selection to work. For example, attaching a click event to a button requires that you select the button first.

Because common jQuery selectors are based on existing CSS selectors, you are probably very familiar with them. However, there are some selectors that are not widely used. In this tutorial, I'll focus on these lesser-known but important selectors.

All selectors (*)

This selector is correctly called a universal selector because it selects all elements in the document, including , class="inline">

, <script></script> or <link> tags. This demo should illustrate my point. <pre class='brush:php;toolbar:false;'>$(&quot;section *&quot;) // Selects all descendants $(&quot;section &gt; *&quot;) // Selects all direct descendants $(&quot;section &gt; * &gt; *&quot;) // Selects all second level descendants $(&quot;section &gt; * &gt; * a&quot;) // Selects 3rd level links </pre> <p>This selector can be very slow if used in combination with other elements. However, it all depends on how the selector is used and in which browser it is executed. In Firefox, <code class="inline">$("#selector > *").find("li") is better than $("#selector > ul").find("li"). Interestingly, Chrome does $("#selector > *").find("li") slightly faster. All browsers execute $("#selector *").find("li") slower than $("#selector ul").find("li"). I recommend you compare performance before using this selector.

Here is a demonstration comparing the execution speed of the all selector.

Animated Selector (:animated)

You can use the :animated selector to select all elements whose animation is still in progress while this selector is running. The only problem is that it will only select elements that are animated using jQuery. This selector is a jQuery extension and does not benefit from the performance improvements of the native querySelectorAll() method.

Also, you cannot detect CSS animations using jQuery. However, you can use the animationend event to detect when the animation ends.

Watch the demo below.

In the above demo, only odd div<code class="inline"> elements are animated before executing $(":animated").css("background","#6F9"); .So, only those div elements will change to green. After that, we call the animate function on the rest of the div element. If you click the button now, all div elements should turn green.

Attribute is not equal to selector ([attr!="value"])

Universal attribute selectors typically detect whether an attribute with a given name or value exists. On the other hand, the [attr!="value"] selector will select all elements that do not have the specified attribute or that attribute exists but is not equal to a specific value. It is equivalent to :not([attr="value"]). Unlike [attr="value"], [attr!="value"] is not part of the CSS specification. Therefore, using $("css-selector").not("[attr='value']") can improve performance in modern browsers.

The following code snippet adds the mismatch class to all li elements whose data-category attribute is not equal to css. This Helpful when debugging or setting correct property values ​​using JavaScript.

$("li[data-category!='css']").each(function() {
  $(this).addClass("mismatch");
  // Adds a mismatch class to filtered out selectors.
  
  $(".mismatch").attr("data-category", attributeValue);
  // Set correct attribute value
});

In the demo, I checked both lists and corrected the value of the element's category attribute.

Contains selector (:contains(text))

This selector is used to select all elements containing the specified string. The match string can be located directly inside the relevant element or within any of its descendants.

The example below should help you understand this selector better. We will add a yellow background to all occurrences of the phrase Lorem Ipsum.

Let’s start with the tags:

<section>
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
    has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p>
  <p>It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of <b>Lorem Ipsum</b>.</p>
  <a href="https://en.wikipedia.org/wiki/Lorem_ipsum">Lorem Ipsum Wikipedia Link</a>
</section>
<section>
  <p>This <span class="small-u">lorem ipsum</span> should not be highlighted.</p>
</section>
<ul>
  <li>A Lorem Ipsum List</li>
  <li>More Elements Here</li>
</ul>

Observe that the phrase Lorem Ipsum appears in seven different places. I intentionally use small caps in one instance to indicate that the match is case-sensitive.

Here is the JavaScript code that highlights all matches:

$("section:contains('Lorem Ipsum')").each(function() {
  $(this).html(
      $(this).html().replace(/Lorem Ipsum/g, "<span class='match-o'>Lorem Ipsum</span>")
    );
});

Quotes around strings are optional. This means that $("section:contains('Lorem Ipsum')") and $("section:contains(Lorem Ipsum)") are both valid in the above snippet . I'm only targeting some elements, so the Lorem Ipsum text within the list elements should remain unchanged. Additionally, the text within the second section element should not be highlighted due to a case mismatch. As you can see in this demo, that's exactly what happens.

有选择器 (:has(selector))

此选择器将选择至少包含一个与给定选择器匹配的元素的所有元素。需要匹配的选择器不必是直接子级。 :has() 不是 CSS 规范的一部分。在现代浏览器中,您应该使用 $("pure-css-selector").has(selector) 而不是 $("pure-css-selector:has(选择器)") 以提高性能。

此选择器的一个可能的应用是操作其中包含特定元素的元素。在我们的示例中,我将更改内部包含链接的所有列表元素的颜色。

这是演示的标记:

<ul>
  <li>Pellentesque <a href="dummy.html">habitant morbi</a> tristique senectus.</li>
  <li>Pellentesque habitant morbi tristique senectus.</li>
  (... more list elements here ...)
  <li>Pellentesque habitant morbi tristique senectus.</li>
  <li>Pellentesque <a href="dummy.html">habitant morbi</a> tristique senectus.</li>
</ul>

以下是更改列表元素颜色的 JavaScript 代码:

$("li:has(a)").each(function(index) {
  $(this).css("color", "crimson");
});

这段代码背后的逻辑非常简单。我循环遍历所有包含链接的列表元素并将其颜色设置为深红色。您还可以操作列表元素内的文本或将它们从 DOM 中删除。我确信这个选择器可以用在很多其他情况下。在 CodePen 上查看此代码的实时版本。

基于索引的选择器

除了像 :nth-child() 这样的 CSS 选择器之外,jQuery 也有自己的一组基于索引的选择器。这些选择器是 :eq(index):lt(index):gt(index)。与基于 CSS 的选择器不同,这些选择器使用从零开始的索引。这意味着 :nth-child(1) 将选择第一个子级,而 :eq(1) 将选择第二个子级。要选择第一个孩子,您必须使用 :eq(0)

这些选择器也可以接受负值。当指定负值时,将从最后一个元素开始向后计数。

:lt(index) 选择索引小于指定值的所有元素。要选择前三个元素,您将使用 :lt(3)。这是因为前三个元素的索引值分别为 0、1 和 2。使用负索引将选择向后计数后到达的元素之前的所有值。同样,:gt(index) 选择索引大于指定值的所有元素。

:lt(4)  // Selects first four elements
:lt(-4) // Selects all elements besides last 4
:gt(4)  // Selects all elements besides first 5
:gt(-4) // Selects last three elements
:gt(-1) // Selects Nothing
:eq(4)  // Selects fifth element
:eq(-4) // Selects fourth element from last

尝试单击演示中的各个按钮以更好地了解索引选择器。

表单选择器

jQuery 定义了许多选择器,以便轻松选择表单元素。例如, :button 选择器将选择所有按钮元素以及按钮类型的元素。同样, :checkbox 将选择所有类型为 checkbox 的输入元素。几乎所有输入元素都定义了选择器。考虑下面的表格:

<form action="#" method="post">
  <div>
    <label for="name">Text Input</label>
    <br>
    <input type="text" name="name" />
    <input type="text" name="name" />
  </div>
  <hr>
  <div>
    <label for="checkbox">Checkbox:</label>
    <input type="checkbox" name="checkbox" />
    <input type="checkbox" name="checkbox" />
    <input type="checkbox" name="checkbox" />
    <input type="checkbox" name="checkbox" />
  </div>
</form>

我在这里创建了两个文本元素和四个复选框。该表单非常基本,但它应该让您了解表单选择器的工作原理。我们将使用 :text 选择器计算文本元素的数量,并更新第一个文本输入中的文本。

var textCount = $(":text").length;
$(".text-elements").text('Text Inputs : ' + textCount);

$(":text").eq(0).val('Added programatically!');

我使用 :text 选择所有文本输入,然后使用 length 方法来计算它们的数量。在第三条语句中,我使用前面讨论的 :eq() 选择器来访问第一个元素,然后设置其值。

请记住,从 jQuery 1.5.2 开始,对于未指定任何 type 属性的元素,:text 返回 true

看看演示。

标头选择器 (:header)

如果您想选择网页上的所有标题元素,可以使用简短的 $(":header") 版本,而不是详细的 $ ("h1 h2 h3 h4 h5 h6") 选择器。此选择器不是 CSS 规范的一部分。因此,首先使用纯 CSS 选择器,然后使用 .filter(":header") 可以获得更好的性能。

例如,假设网页上有一个 article 元素,并且它具有三个不同的标题。现在,为了简洁起见,您可以使用 $("article :header") 而不是 $("article h1,article h2,article h3")。为了使其更快,您可以使用 $("article").filter(":header")。这样您就可以两全其美。

要对所有标题元素进行编号,您可以使用以下代码。

$("article :header").each(function(index) {
  $(this).text((index + 1) + ": " + $(this).text());
  // Adds numbers to Headings
});

尝试一下随附的演示。

最终想法

在本教程中,我讨论了使用 jQuery 时可能遇到的不常见选择器。虽然大多数选择器都有可供您使用的替代方案,但了解这些选择器的存在仍然是件好事。

我希望您在本教程中学到了一些新东西。如果您有任何问题或建议,请评论。

The above is the detailed content of The rephrased title is: Rarely Used jQuery Selectors. 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: 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.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool