Selectors in jQuery

Get introduced to selectors and explore the different types of selectors in jQuery.

What are selectors?

jQuery selectors find or extract DOM elements using specific patterns and identifiers. The patterns for finding these elements are specified within quotes in the $() function. jQuery adopts some of these patterns from CSS selector patterns, whereas other patterns are specific to jQuery.

Types of selectors

The following types of patterns can be used in jQuery:

  • Tag name
  • Id
  • Class
  • Attribute
  • Child
  • Descendants

Based on the pattern used, the different types of selectors in jQuery are explained below.

Select by tag name

These are the most used selectors in jQuery. They use tag names such as div and p to return a list of all elements on the web page with the given tag name.

In the code shown above, the text “This is a paragraph element” is appended to all the p elements on the web page. These paragraph elements initially contained no text: this can be seen in the highlighted lines 8-9 and 11-12 of the HTML tab.

Select by id

We can also select a particular element in jQuery by specifying its id. Since the id is unique to every element, the selector returns only one element. Because of this, the selector starts with #, followed by the id of the element.

In the code above, the text is appended only to the paragraph with the id of 123, shown in highlighted lines 8-9 of the HTML tab.

Select by class

Apart from the id, we can also select elements based on their class. The only difference is that we add . instead of # before the class name. The selector then returns a list of elements with the given class name.

In the above code, the text is only appended to a div and p element with class=boldText, highlighted in lines 7-8 and 13-14 on the HTML tab.

Select by attribute and attribute value

We can select elements based on attributes such as class and id. Moreover, we can also select elements based on attribute values. We enclose the attributes or attribute values in square brackets as follows:

  • [id] - selects all elements with the attribute id
  • [class='boldText'] - selects all elements with the class of boldText

The code for appending text to elements with class boldText can be rewritten using attribute value as shown above.

Selecting by attribute is slower than selecting by id or class, but it can select elements by other attributes, making it more flexible.

Creating new elements using $

The $() function can also create new HTML elements apart from selecting HTML elements using different patterns.

We can write down the desired HTML element within quotes and pass it to the $() function. For example:

$() creates only the element and does NOT add it to the web page. Hence the web page output is empty.