What you'll learn
How to select by tag, class and id, and how to narrow a selection with .first(), .eq() and .filter().
Why it matters
Every jQuery action starts with a selection. The more precisely you can select, the less code you need.
Explanation
jQuery selectors are CSS selectors:
"p": all paragraphs.".note": all elements with classnote."#title": the element with idtitle."ul li": list items inside a list."a[href^='https']": links whose address starts with https.
You can narrow a selection afterwards:
.first()and.last().eq(n): the item at index n (starting at 0).filter(".x"): keep only those that match.x
Example
<ul>
<li class="fruit">Apple</li>
<li class="fruit">Banana</li>
<li class="veg">Carrot</li>
<li class="fruit">Date</li>
</ul>
<p id="count"></p>
<script>
$(function () {
$(".fruit").css("color", "tomato");
$("li").eq(2).css("font-weight", "bold");
$("#count").text($(".fruit").length + " fruits");
});
</script>Step-by-step walkthrough
$(".fruit")selects Apple, Banana and Date and colours them.$("li").eq(2)is the third list item (index 2), Carrot, which becomes bold.$(".fruit").lengthcounts the selection: 3.- The count is written into the paragraph:
3 fruits.
Try it yourself
Make only the last li green using .last().
SelectorsjQuery
Common mistakes
- Missing the dot or hash in
".class"and"#id". - Expecting
.eq(1)to be the first. Index starts at 0. - Using the same id twice, so only one element matches.
- Not checking
.length: an empty selection silently does nothing.
Quick quiz
Summary
- jQuery uses CSS selectors inside
$(). .first(),.last(),.eq(n),.filter()narrow a selection..lengthtells you how many matched.
Next: changing the page.