CSS Selectors in jQuery

  • jQuery
  • 5 mins read

Summary: In this tutorial, you will learn about the CSS Selectors in jQuery and how to use them effectively in your programs.

The fact that jQuery is so simple to use is undoubtedly one of its most appealing features. You're presumably acquainted with CSS, and you're aware that the hash symbol (#) is used to pick an element by its ID. A period (.) is used to pick an element by its class, and so on. These selectors (and others) are available in jQuery for selecting elements from the DOM. It also has backward compatibility, which is fantastic. So, even if the CSS selector you're using doesn't work in Internet Explorer 7 and below, it will be in jQuery. However, tremendous power comes with great responsibility, and many of these pickers are wasteful in terms of computation. The simplest way to choose an element is to use its ID, as seen below:

jQuery: CSS Selector by ID Example

$("#header");
$("#maincontent");

This method will always be faster than choosing by a class or a tag name, which are the other frequent methods; for example:

jQuery: by Class Example

$(".column");
$(".header");
$("body");

$("div");

Explanation

There are two reasons why picking by ID is the preferred method. First, because JavaScript has its own mechanism for choosing by ID—document.getElementById("header")— jQuery can simply call that function when it detects that you've passed in an ID. Second, there should never be more than one element with the same ID, so once it finds a result, it stops looking.

It is your responsibility to guarantee that an ID appears just once on a page. If there are many elements with the same ID, Javascript (and hence jQuery) will only return the first one. Having an ID on more than one element is invalid HTML.

If you're looking for something by class, there could be a lot of results, so JavaScript has to keep looking through the whole DOM. If you can choose an element based on its ID, do so. Another point worth highlighting is how jQuery handles selector results. Regardless matter whether one or fifty elements are returned, the results will return an array-like structure (it's not an array, but it behaves like one, as explained further down). Assume you have one paragraph on a page and you run $("p"). Take a look at the results:

[<p>Hey</p>]

You get this if you have a few more:

[<p>Hey</p>, <p>Hey</p>, <p>Hey</p>, <p>Hey</p>]

One advantage of this is that you can quickly determine the amount of items returned by using .length on the result, as shown below because the result behaves just like a JavaScript array:

$("p").length; // 4

In versions of jQuery prior to 1.8, you can use the jQuery function $("p").size(), however, all it does is return the result of using .length, therefore developers usually use .length.

At this point, it may appear that jQuery simply returns a standard array, but it does not. It yields a jQuery object. This jQuery object is similar to the ordinary objects you saw in Chapter 1. It includes all of the jQuery properties and methods, as well as the elements from the selector you used. The jQuery object can be thought of as an improved array. It has a list of DOM elements at its foundation, but it is much more than that. Keep in mind that when you run $("p") and obtain what appears to be an array, it isn't. It is, in fact, a jQuery object.

One of the most perplexing aspects of jQuery for new users is the fact that some methods are called on every element they return, while others are not. Assume you have a list of four paragraphs and wish to assign a class to each of them. The following will suffice:

$("p").addClass("paragraph");

The method addClass() is self-explanatory. It just gives the items a class. Notably, the addClass() method is called on each element in the result set. It's also worth noting that you don't have to loop over them. If you have a set of elements and call a method, jQuery will almost always execute the looping for you. This is quite handy, but it might be a little confusing, so keep in mind that jQuery will always loop for you if it can.

You can, of course, use jQuery to read CSS selectors, so you can give it very complicated selectors, like:

$("div>ul a");
$("div#main p strong");

$("div.main p>li a");

However, the more complicated those selections are, the longer they take to run and the slower your code will perform. Because jQuery parses CSS selectors from right to left, the last example does:

All anchor pieces are located.
Removes anchor elements that are not contained within a list item.
Removes all remaining elements save those contained within a li> that is an immediate child of a paragraph.
Selects only the remaining elements that belong to the main class.
Only those left that is within a div with the primary class is chosen. That's a lot of effort simply to find a few links. This is something to be careful of and keep in mind while picking which selector to employ.

Reference: https://api.jquery.com/category/selectors/

Video Tutorial

CSS Selectors - jQuery

Useful Resources:

A Comprehensive Look at jQuery Selectors - SitePoint

August 2, 2016 - SitePoint

A Comprehensive Look at jQuery Selectors  SitePoint...

jQuery Selectors - DZone

July 5, 2015 - DZone

jQuery Selectors  DZone...

Create Custom CSS Selectors in jQuery - HTML Goodies

September 18, 2017 - HTML Goodies

Create Custom CSS Selectors in jQuery  HTML Goodies...