神刀安全网

Uncommon jQuery Selectors

Selectors are of vital importance. Most jQuery methods require some kind of element selection to be of any use. For instance, attaching a click event to a button requires you to select the button first. 

Since common jQuery selectors are based on existing CSS selectors, you might be well versed in them. However, there are also a few selectors that are not used as much. In this tutorial, I will focus on these lesser known but important selectors.

All Selector (*)

This selector is rightly called the universal selector because it selects all the elements in the document, including the <head> , <body> , <script> or <link tags.  This demo should illustrate my point.

$("section *")         // Selects all descendants $("section > *")       // Selects all direct descendants $("section > * > *")   // Selects all second level descendants $("section > * > * a") // Selects 3rd level links

This selector is extremely slow if used in combination with other elements. However, it all depends on how the selector is used and which browser it is executed in. In Firefox, $("#selector > *").find("li") is slower than  $("#selector > ul").find("li") . Interestingly, Chrome executes   $("#selector > *").find("li") slightly more quickly. All browsers execute  $("#selector *").find("li") more slowly than  $("#selector  ul").find("li") . I would suggest that you compare the performance before using this selector. 

Here is a demo that compares 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 when this selector runs. The only issue is that it will only select elements which were animated using jQuery. This selector is a jQuery extension and does not benefit from the performance boost that comes with the native  querySelectorAll() method. 

Also, you can’t detect CSS animations using jQuery. You can, however, detect when the animation ends using the animationend event.

Take a look at the following demo .

In the demo above, only the odd div elements are animated before executing  $(":animated").css("background","#6F9"); . As a result, only those div elements change to green. Just after that, we call the animate function on the rest of the div elements. If you click on the button now, all div elements should turn green.

Attribute Not Equal Selector ([attr!="value"])

Common attribute selectors usually detect if an attribute with a given name or value exists. On the other hand, the [attr!="value"] selector will select all elements that don’t have the specified attribute or where the attribute exists but is not equal to a particular value. It is equivalent to  :not([attr="value"]) . Unlike  [attr="value"][attr!="value"] is not part of the CSS specification. As a result, using  $("css-selector").not("[attr='value']") can improve performance in modern browsers. 

The snippet below adds a mismatch class to all li elements whose data-category attribute is not equal to css . This can be helpful during debugging or setting the correct attribute value 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 go through two lists and correct the value of the category attributes of elements.

Contains Selector (:contains(text))

This selector is used to select all elements which contain the specified string. The matching string can be directly inside the concerned element or inside any of its descendants.

The example below should help you get a better understanding of this selector.  We will be adding a yellow background to all occurrences of the phrase Lorem Ipsum .

Let’s begin with the markup:

<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 occurs in seven different locations. I have deliberately used small caps in one of these instances to show that the matching is case sensitive. 

Here’s the JavaScript code to highlight all matches:

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

The quotes around the string are optional. This implies that both $("section:contains('Lorem Ipsum')") and  $("section:contains(Lorem Ipsum)") will be valid in the snippet above. I am only targeting the section element, so the Lorem Ipsum text inside the list elements should remain unchanged. Moreover, due to non-matching case, the text inside the second section element should not be highlighted either. As you can see in this demo , this is exactly what happens.

Has Selector (:has(selector))

This selector will select all elements which contain at least one element that matches a given selector. The selector that needs to be matched doesn’t have to be a direct child. :has() is not part of the CSS specification. In modern browsers, you should use  $("pure-css-selector").has(selector) instead of  $("pure-css-selector:has(selector)") for improved performance. 

One possible application of this selector is the manipulation of elements that contain a specific element inside them. In our example, I will be changing the color of all list elements that contain a link inside them.

This is the markup for the demo:

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

Here’s the JavaScript code to change the color of the list elements:

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

The logic behind this code is pretty straightforward. I loop through all the list elements that contain a link and set their color to crimson. You could also manipulate the text inside the list elements or remove them from the DOM. I am sure this selector can be used in a lot of other situations. Check out a live version of this code on CodePen .

Index-Based Selectors

Besides CSS selectors like :nth-child() , jQuery also has its own set of index-based selectors. These selectors are :eq(index) , :lt(index) , and  :gt(index) . Unlike CSS-based selectors, these selectors use zero-based indexing. This implies that while :nth-child(1) will select the first child, :eq(1) will select the second child. To select the first child you will have to use :eq(0)

These selectors can also accept negative values. When negative values are specified, counting is done backwards starting from the last element.

:lt(index) selects all elements which are at an index less than the specified value. To select the first three elements, you will use :lt(3) . This is because the first three elements will have index values 0, 1 and 2 respectively. Using a negative index will select all values before the element that we reached after counting backwards. Similarly, :gt(index) selects all elements with index greater than the specified value.

: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

Try clicking on various buttons in the demo to get a better understanding of index selectors.

Form Selectors

jQuery defines a lot of selectors for easy selection of form elements. For example, the :button selector will select all button elements as well as elements with type button. Similarly, :checkbox will select all input elements with type checkbox. There are selectors defined for almost all input elements. Consider the form below:

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

I have created two text elements here and four checkboxes. The form is pretty basic, but it should give you an idea of how form selectors work. We will count the number of text elements using the :text selector and also update the text in the first text input. 

var textCount = $(":text").length; $(".text-elements").text('Text Inputs : ' + textCount);  $(":text").eq(0).val('Added programatically!');

I use :text to select all text inputs and then the length method to calculate their number. In the third statement, I use the previously discussed :eq() selector to access the first element and later set its value. 

Keep in mind that as of jQuery 1.5.2, :text returns true for elements that do not have any type attribute specified.

Have a look at the demo .

Header Selector (:header)

If you ever want to select all the heading elements on a webpage, you can use the short $(":header") version instead of the verbose  $("h1 h2 h3 h4 h5 h6") selector. This selector is not part of the CSS specification. As a result, better performance could be achieved using a pure CSS selector first and then using  .filter(":header")

For instance, assume that there is an article element on a webpage and it has three different headings. Now, you could use $("article :header") instead of  $("article h1, article h2, article h3") for brevity. To make it even faster, you could use  $("article").filter(":header") . This way you have the best of both worlds.

To number all the heading elements, you could use the following code.

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

Try this accompanying demo .

Final Thoughts

In this tutorial, I discussed uncommon selectors that you might encounter when using jQuery. While most of these selectors have alternatives that you can use, it is still good to know that these selectors exist.

I hope you learned something new in this tutorial. If you have any questions or suggestions, please do comment.

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Uncommon jQuery Selectors

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址