jQuery Tutorial menu

jQuery Selectors

Selectors tell jQuery which elements you want to work with. They use the same text as CSS selectors, plus a few extras.

The Three Basic Selectors

SelectorFindsExample
Tag nameEvery element of that tag$("p")
#idThe one element with that id$("#menu")
.classEvery element with that class$(".price")

Example

html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
</head>
<body>

<h3 id="shop">Karachi Book Centre</h3>
<p class="price">Urdu Dictionary: Rs 900</p>
<p class="price">Maths Guide: Rs 650</p>
<p>Open 10 AM to 9 PM</p>

<button id="b1">Select p</button>
<button id="b2">Select #shop</button>
<button id="b3">Select .price</button>

<script>
$(function () {
  function reset() { $("*").css("background", ""); }
  $("#b1").click(function () { reset(); $("p").css("background", "yellow"); });
  $("#b2").click(function () { reset(); $("#shop").css("background", "yellow"); });
  $("#b3").click(function () { reset(); $(".price").css("background", "yellow"); });
});
</script>

</body>
</html>
Try it Yourself »

Combining Selectors

SelectorMeaning
$("p.price")<p> elements with class price
$("h1, h2, h3")All h1, h2 and h3 elements
$("ul li")Every <li> inside a <ul> (any level)
$("ul > li")Only <li> elements directly inside a <ul>
$("*")Every element
$(this)The element that triggered the current event

Attribute Selectors

Find elements by their attributes, written in square brackets:

Example

javascript
$("[href]")                  // elements that have an href
$("a[target='_blank']")      // links that open in a new tab
$("input[type='email']")     // email input boxes
$("a[href^='https']")        // links whose href starts with https
$("img[src$='.png']")        // images whose src ends with .png

Position Filters

jQuery has filters to pick elements by position. Positions start at 0.

FilterPicks
:first / :lastThe first / last matching element
:even / :oddPositions 0, 2, 4... / 1, 3, 5...
:eq(2)The element at position 2
:first-childElements that are the first child of their parent

Example

html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<style>
table { border-collapse: collapse; }
td { padding: 6px 14px; border: 1px solid #ccc; }
</style>
</head>
<body>

<table>
  <tr><td>Ali</td><td>82</td></tr>
  <tr><td>Ayesha</td><td>95</td></tr>
  <tr><td>Bilal</td><td>67</td></tr>
  <tr><td>Sana</td><td>88</td></tr>
</table>

<script>
$(function () {
  $("tr:even").css("background", "#e8f1fa");
  $("tr:first").css("font-weight", "bold");
});
</script>

</body>
</html>
Try it Yourself »

Filters like :first, :even and :eq() are jQuery extras, not real CSS. In jQuery 3 the methods .first(), .last(), .even(), .odd() and .eq(2) are preferred, for example $("tr").eq(2), because they are faster.

Form Filters

FilterPicks
:inputAll input, select, textarea and button elements
:checkedChecked checkboxes and radio buttons
:selectedSelected options in a select box
:disabledDisabled form elements
:visible / :hiddenElements that are shown / hidden

Example

javascript
let count = $("input[type='checkbox']:checked").length;
console.log(count + " subjects selected");

How Many Did I Find?

A jQuery selection works like an array. .length tells you how many elements matched. If nothing matched, it is 0, and methods simply do nothing; there is no error.

Example

javascript
if ($("#cart").length) {
  console.log("The cart exists on this page");
}

Exercise

Exercise

Which selector finds only the input elements whose type is "email"?

Learn jQuery with a teacher

Join the Web Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp