jQuery selector

Using JavaScript document.getElementById(), document.getElementsByClass(), etc., you can select an HTML element and apply operations on it. In jQuery, an HTML element or group of HTML elements (based on a criteria like class or tag) could be selected using the notation $ (dollar) symbol followed by parenthesis.

In this tutorial, you will learn about different kinds of HTML element selectors with syntax and examples.

Syntax – jQuery selector

Following is the syntax to select an element in jQuery using tag :

ADVERTISEMENT

1. Select HTML element using tag

To select an element in jQuery using tag, use the following syntax.

$("tag")

Examples

$("p") // to select all paragraph elements
$("div") // to select all div elements
$("h2") // to select all heading2 elements
$("a") // to select all anchor elements
$("table") // to select all tables

2. Select HTML element using id

To select an element in jQuery using id, use # (hash) symbol infront of the actual id you provide.

$("#id")

Examples

$("#personName") // to select element with id="personName"
$("#pAge") // to select element with id="pAge"

3. Select HTML element using class

To select elements in jQuery using class, use . (dot) symbol infront of the actual class you provide

$(".class")

Examples

$(".roundButton") // to select elements with class="roundButton"
$(".book") // to select elements with class="book"

4. Select HTML element using combinations of Tag, ID and Class

Combinations of tag, id and class could be used to filter specific HTML elements that would like to manipulate. This is similar to how you provide in a css file.

Examples

$("p.highlite") // to select paragraph elements with class="highlite"
$("div#mainTitle") // to select div element with id="mainTitle"
$("div .btn") // to select elements with class="btn" within the child elements of div node

Examples – jQuery selector

Following examples help you understand the usage of jQuery selector.

1. Example – Select elements using Tag

Following example demonstrates how to use jQuery selector to select all HTML elements with p (paragraph) tag.

2. Example – Select elements using ID

In the following example, jQuery selector is used to select HTML element with a specific ID.

3. Example – Select elements using Class

In the following example, jQuery selector is used to select HTML element with a specific Class value.

4. Example – Select elements using Tag and Class

In the following example, jQuery selector is used to select HTML element(s) with a specific combination of tag and class.

5. Example – Select elements with multiple combinations of Tags, Classes and IDs

The following example takes the selection of elements to next level. We use a combination of tag, class and ID to select HTML Element(s).

Conclusion

In this jQuery Tutorial, we have learnt jQuery selector() with the help of examples.