The rephrased title is: 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.
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>$("section *") // Selects all descendants
$("section > *") // Selects all direct descendants
$("section > * > *") // Selects all second level descendants
$("section > * > * a") // Selects 3rd level links
</pre><div class="contentsignin">Copy after login</div></div>
<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.
1 2 3 4 5 6 7 |
|
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
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:
1 2 3 4 5 |
|
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(选择器)")
以提高性能。
此选择器的一个可能的应用是操作其中包含特定元素的元素。在我们的示例中,我将更改内部包含链接的所有列表元素的颜色。
这是演示的标记:
1 2 3 4 5 6 7 |
|
以下是更改列表元素颜色的 JavaScript 代码:
1 2 3 |
|
这段代码背后的逻辑非常简单。我循环遍历所有包含链接的列表元素并将其颜色设置为深红色。您还可以操作列表元素内的文本或将它们从 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)
选择索引大于指定值的所有元素。
1 2 3 4 5 6 7 |
|
尝试单击演示中的各个按钮以更好地了解索引选择器。
表单选择器
jQuery 定义了许多选择器,以便轻松选择表单元素。例如, :button
选择器将选择所有按钮元素以及按钮类型的元素。同样, :checkbox
将选择所有类型为 checkbox 的输入元素。几乎所有输入元素都定义了选择器。考虑下面的表格:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
我在这里创建了两个文本元素和四个复选框。该表单非常基本,但它应该让您了解表单选择器的工作原理。我们将使用 :text
选择器计算文本元素的数量,并更新第一个文本输入中的文本。
1 2 3 4 |
|
我使用 :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")
。这样您就可以两全其美。
要对所有标题元素进行编号,您可以使用以下代码。
1 2 3 4 |
|
尝试一下随附的演示。
最终想法
在本教程中,我讨论了使用 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.
