We are still cooking the magic in the way!
jQuery & DOM Manipulation
jQuery Selectors - Part 1
Mastering jQuery Selectors
Selectors are the foundation of jQuery. They allow you to find and select HTML elements to manipulate. jQuery uses CSS-style selector syntax, making it familiar and powerful.
Why Selectors Matter
Before you can do anything with an element, you need to select it. jQuery selectors make this incredibly easy and flexible.
💡 Key Point: If you know CSS selectors, you already know jQuery selectors! They use the exact same syntax.
Basic Selectors
1. Element Selector
Select all elements of a specific type:
// Select all paragraphs
$('p')
// Select all divs
$('div')
// Select all links
$('a')
// Example: Hide all paragraphs
$('p').hide();
2. ID Selector
Select a single element by its unique ID:
// Select element with id="header"
$('#header')
// Select element with id="loginBtn"
$('#loginBtn')
// Example: Change text of element with id="title"
$('#title').text('New Title');
📝 Remember: IDs should be unique on a page. Use # prefix for ID selectors.
3. Class Selector
Select all elements with a specific class:
// Select all elements with class="highlight"
$('.highlight')
// Select all elements with class="btn"
$('.btn')
// Example: Add a class to all elements with class "card"
$('.card').addClass('shadow');
Real-World Example
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
.highlight { background: yellow; }
.hidden { display: none; }
</style>
<script>
$(function() {
// Element selector - hide all paragraphs
$('#hideP').click(function() {
$('p').addClass('hidden');
});
// ID selector - change specific heading
$('#changeTitle').click(function() {
$('#mainTitle').text('Title Changed!');
});
// Class selector - highlight all cards
$('#highlightCards').click(function() {
$('.card').addClass('highlight');
});
});
</script>
</head>
<body>
<h1 id="mainTitle">Original Title</h1>
<div class="card">Card 1</div>
<div class="card">Card 2</div>
<div class="card">Card 3</div>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<button id="hideP">Hide Paragraphs</button>
<button id="changeTitle">Change Title</button>
<button id="highlightCards">Highlight Cards</button>
</body>
</html>
Universal Selector
Select ALL elements on the page:
// Select everything
$('*')
// Example: Add a class to all elements
$('*').addClass('animated');
⚠️ Warning: Use the universal selector (*) sparingly. It can impact performance on large pages since it selects EVERY element.
Multiple Selectors
Select multiple different elements at once:
// Select all h1, h2, and h3 elements
$('h1, h2, h3')
// Select multiple classes
$('.warning, .error, .alert')
// Mixed selectors
$('#header, .nav, p')
// Example: Hide all headings and paragraphs
$('h1, h2, h3, p').hide();
Hierarchy Selectors
Descendant Selector (space)
Select elements inside other elements:
// Select all paragraphs inside divs
$('div p')
// Select all links inside the navigation
$('#nav a')
// Select all list items inside elements with class "menu"
$('.menu li')
HTML Example:
<div id="container">
<p>This paragraph will be selected</p>
<section>
<p>This one too (any level deep)</p>
</section>
</div>
<script>
// Selects BOTH paragraphs
$('#container p').css('color', 'blue');
</script>
Child Selector (>)
Select only direct children:
// Select only direct paragraph children of divs
$('div > p')
// Select direct list items only
$('#menu > li')
HTML Example:
<div id="container">
<p>Direct child - WILL be selected</p>
<section>
<p>Grandchild - will NOT be selected</p>
</section>
</div>
<script>
// Selects only the direct child paragraph
$('#container > p').css('color', 'blue');
</script>
💡 Difference:
- Descendant (space): Selects at ANY level deep
- Child (>): Selects only DIRECT children
Attribute Selectors
Select elements based on their attributes:
// Elements with a specific attribute
$('[href]') // All elements with href attribute
$('[data-id]') // All elements with data-id attribute
// Attribute equals specific value
$('[type="text"]') // All text inputs
$('[class="button"]') // Elements with exact class "button"
// Attribute contains value
$('[href*="google"]') // Links containing "google"
$('[class*="btn"]') // Elements with "btn" anywhere in class
// Attribute starts with value
$('[href^="https"]') // Links starting with "https"
$('[id^="user"]') // IDs starting with "user"
// Attribute ends with value
$('[href$=".pdf"]') // Links ending with .pdf
$('[src$=".jpg"]') // Images ending with .jpg
Practical Examples
// Open all external links in new tab
$('a[href^="http"]').attr('target', '_blank');
// Style all email links
$('a[href^="mailto:"]').css('color', 'green');
// Find all required inputs
$('input[required]').css('border', '2px solid red');
// Select all data attributes
$('[data-toggle="modal"]').click(function() {
// Handle modal opening
});
Filter Selectors
:first and :last
// First paragraph
$('p:first')
// Last list item
$('li:last')
// Example: Highlight first and last items
$('li:first').css('background', 'lightgreen');
$('li:last').css('background', 'lightblue');
:even and :odd
// Even numbered elements (0, 2, 4...)
$('tr:even')
// Odd numbered elements (1, 3, 5...)
$('tr:odd')
// Example: Stripe a table
$('tr:even').css('background', '#f0f0f0');
$('tr:odd').css('background', '#ffffff');
📝 Note: jQuery uses zero-based indexing, so :even selects the 1st, 3rd, 5th elements (indices 0, 2, 4).
:eq(), :lt(), :gt()
// Element at specific index
$('li:eq(2)') // Third list item (index 2)
// Elements with index less than
$('li:lt(3)') // First 3 list items (indices 0, 1, 2)
// Elements with index greater than
$('li:gt(2)') // All items after the third (indices 3+)
// Example: Select specific range
$('li:gt(1):lt(4)') // Items 2, 3, 4 (indices 2, 3, 4)
Selector Performance Tips
💡 Performance Best Practices:
- ID selectors are fastest - Use when possible:
$('#myId') - Be specific -
$('div.menu')is faster than$('.menu') - Cache selectors - Store in variables if used multiple times
❌ Bad (selects multiple times):
$('#menu').addClass('active');
$('#menu').show();
$('#menu').fadeIn();
✅ Good (cache the selector):
var $menu = $('#menu');
$menu.addClass('active');
$menu.show();
$menu.fadeIn();
// Or even better with chaining:
var $menu = $('#menu')
.addClass('active')
.show()
.fadeIn();
🎯 Practice Exercise:
Create an HTML page with:
- A list of 5 items with class "item"
- The third item should have id="special"
- Add buttons to:
- Highlight all even items
- Hide the first item
- Change the text of #special
- Add a border to the last item
💡 Solution
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(function() {
$('#btn1').click(function() {
$('.item:even').css('background', 'yellow');
});
$('#btn2').click(function() {
$('.item:first').hide();
});
$('#btn3').click(function() {
$('#special').text('I am special!');
});
$('#btn4').click(function() {
$('.item:last').css('border', '3px solid red');
});
});
</script>
</head>
<body>
<ul>
<li class="item">Item 1</li>
<li class="item">Item 2</li>
<li class="item" id="special">Item 3</li>
<li class="item">Item 4</li>
<li class="item">Item 5</li>
</ul>
<button id="btn1">Highlight Even</button>
<button id="btn2">Hide First</button>
<button id="btn3">Change Special</button>
<button id="btn4">Border Last</button>
</body>
</html>
Summary
In this lesson, you learned:
- Basic selectors: element, ID (#), and class (.)
- Universal selector (*) selects all elements
- Multiple selectors using comma separation
- Hierarchy selectors: descendant (space) and child (>)
- Attribute selectors for finding elements by attributes
- Filter selectors: :first, :last, :even, :odd, :eq()
- Performance tips for efficient selection
In the next lesson, we'll explore more advanced selectors and filtering methods!