We are still cooking the magic in the way!
jQuery & DOM Manipulation
jQuery Selectors - Part 2
Advanced jQuery Selectors
In this lesson, we'll explore more powerful selector techniques including form selectors, content filters, visibility filters, and traversal methods that give you precise control over element selection.
Form Selectors
jQuery provides specialized selectors for working with form elements:
// Select all input elements
$(':input') // All input, textarea, select, button
// Select by input type
$(':text') // All text inputs
$(':password') // All password inputs
$(':radio') // All radio buttons
$(':checkbox') // All checkboxes
$(':submit') // All submit buttons
$(':button') // All buttons
$(':file') // All file inputs
$(':image') // All image inputs
// Select by state
$(':enabled') // All enabled form elements
$(':disabled') // All disabled form elements
$(':checked') // All checked checkboxes/radios
$(':selected') // All selected options in select
Practical Form Examples
// Get values of all text inputs
var values = [];
$(':text').each(function() {
values.push($(this).val());
});
// Disable all submit buttons
$(':submit').prop('disabled', true);
// Count checked checkboxes
var checkedCount = $(':checkbox:checked').length;
// Get selected option text
var selectedText = $('#country :selected').text();
// Validate required fields
$(':input[required]').each(function() {
if ($(this).val() === '') {
$(this).css('border', '2px solid red');
}
});
Complete Form Example
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$(function() {
// Check all checkboxes
$('#checkAll').click(function() {
$(':checkbox').prop('checked', true);
});
// Uncheck all
$('#uncheckAll').click(function() {
$(':checkbox').prop('checked', false);
});
// Count selections
$('#count').click(function() {
var count = $(':checkbox:checked').length;
alert(count + ' items checked');
});
// Enable/disable submit based on checkbox
$('#agree').change(function() {
$(':submit').prop('disabled', !this.checked);
});
});
</script>
</head>
<body>
<form>
<label><input type="checkbox" name="item1"> Item 1</label><br>
<label><input type="checkbox" name="item2"> Item 2</label><br>
<label><input type="checkbox" name="item3"> Item 3</label><br>
<br>
<label><input type="checkbox" id="agree"> I agree</label><br>
<br>
<button type="button" id="checkAll">Check All</button>
<button type="button" id="uncheckAll">Uncheck All</button>
<button type="button" id="count">Count Checked</button>
<br><br>
<button type="submit" disabled>Submit</button>
</form>
</body>
</html>
Content Filters
Select elements based on their content:
// Elements containing text
$(':contains("Hello")') // Elements with "Hello" in text
// Empty elements
$(':empty') // Elements with no children
// Elements with children
$(':parent') // Elements that are parents
// Elements containing specific element
$('div:has(p)') // Divs containing paragraphs
$('li:has(a)') // List items containing links
Content Filter Examples
// Highlight paragraphs containing "important"
$('p:contains("important")').css('background', 'yellow');
// Hide empty paragraphs
$('p:empty').hide();
// Find divs that have images
$('div:has(img)').addClass('has-image');
// Style list items without links
$('li:not(:has(a))').css('color', 'gray');
// Remove empty list items
$('li:empty').remove();
Visibility Filters
Select elements based on their visibility:
// Visible elements
$(':visible')
$('div:visible')
$('p:visible')
// Hidden elements
$(':hidden')
$('div:hidden')
$('p:hidden')
📝 Note: An element is considered hidden if:
- display: none
- Width and height are 0
- A parent element is hidden
Visibility Examples
// Count visible divs
var visibleCount = $('div:visible').length;
// Show all hidden paragraphs
$('p:hidden').fadeIn();
// Toggle visibility of hidden elements
$('#toggleBtn').click(function() {
$('.content:hidden').slideDown();
$('.content:visible').slideUp();
});
Negative/NOT Selector
Exclude elements from selection:
// All paragraphs EXCEPT those with class "special"
$('p:not(.special)')
// All inputs EXCEPT checkboxes
$(':input:not(:checkbox)')
// All divs EXCEPT the first one
$('div:not(:first)')
// All links without target attribute
$('a:not([target])')
// Multiple exclusions
$('li:not(.active):not(.disabled)')
NOT Selector Examples
// Style all paragraphs except the first
$('p:not(:first)').css('margin-top', '20px');
// Disable all inputs except submit buttons
$(':input:not(:submit)').prop('disabled', true);
// Hide all divs without the "keep" class
$('div:not(.keep)').hide();
// Add required to all text inputs except optional ones
$(':text:not(.optional)').prop('required', true);
Traversal Methods
After selecting elements, you can traverse the DOM to find related elements:
Finding Relatives
// Parent element
$('#child').parent()
// All ancestors
$('#element').parents()
// Ancestors up to selector
$('#element').parentsUntil('#container')
// Children
$('#parent').children()
// All descendants
$('#parent').find('p')
// Siblings
$('#element').siblings()
// Next sibling
$('#element').next()
// Previous sibling
$('#element').prev()
// Next all siblings
$('#element').nextAll()
// Previous all siblings
$('#element').prevAll()
Traversal Examples
<div id="container">
<div class="parent">
<p id="para1">Paragraph 1</p>
<p id="para2" class="highlight">Paragraph 2</p>
<p id="para3">Paragraph 3</p>
</div>
</div>
<script>
// Get parent of para2
$('#para2').parent().css('border', '2px solid blue');
// Get all siblings of para2
$('#para2').siblings().css('color', 'gray');
// Get next sibling
$('#para2').next().css('font-weight', 'bold');
// Get previous sibling
$('#para2').prev().css('font-style', 'italic');
// Find all paragraphs inside container
$('#container').find('p').addClass('found');
// Get children of parent
$('.parent').children().css('padding', '10px');
</script>
Filtering Methods
Refine your selections further:
// Filter by selector
$('p').filter('.highlight')
// Filter by function
$('li').filter(function(index) {
return index % 2 === 0; // Even indices
});
// First element
$('p').first()
// Last element
$('p').last()
// Element at index
$('p').eq(2)
// Slice range
$('li').slice(1, 4) // Elements 1, 2, 3
// Check if selection matches
if ($('#myDiv').is('.active')) {
// Do something
}
// Check if selection has descendants
if ($('#myDiv').has('p').length) {
// Has paragraphs
}
Filtering Examples
// Highlight even paragraphs
$('p').filter(function(index) {
return index % 2 === 0;
}).css('background', 'yellow');
// Get first and last items
$('li').first().addClass('first-item');
$('li').last().addClass('last-item');
// Get specific range
$('li').slice(2, 5).css('color', 'red');
// Filter by data attribute
$('.item').filter(function() {
return $(this).data('price') > 100;
}).addClass('expensive');
// Check if element has class
if ($('#box').is('.active')) {
console.log('Box is active');
}
Chaining Selectors and Traversal
Combine selectors and traversal for powerful queries:
// Find parent, then siblings, then filter
$('#element')
.parent()
.siblings()
.filter('.active')
.css('color', 'red');
// Find children, filter, then find descendants
$('#container')
.children('div')
.filter(':visible')
.find('p')
.addClass('highlight');
// Complex traversal
$('#list')
.find('li')
.filter(function() {
return $(this).text().length > 10;
})
.first()
.css('font-weight', 'bold');
end() Method
Return to previous selection in chain:
$('#container')
.find('p') // Select paragraphs
.css('color', 'blue') // Style paragraphs
.end() // Back to #container
.find('span') // Now select spans
.css('color', 'red'); // Style spans
// Without end(), you'd need to reselect:
$('#container').find('p').css('color', 'blue');
$('#container').find('span').css('color', 'red');
💡 Pro Tip: Use .end() when you need to work with multiple related selections without repeating the base selector.
🎯 Advanced Exercise:
Create a task management interface with:
- A list of tasks (some marked with class "completed")
- Checkboxes for each task
- Buttons to:
- Show only incomplete tasks
- Show only completed tasks
- Show all tasks
- Mark checked tasks as complete
- Remove completed tasks
💡 Solution
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
.completed {
text-decoration: line-through;
color: gray;
}
.task {
padding: 10px;
margin: 5px 0;
}
</style>
<script>
$(function() {
// Show only incomplete
$('#showIncomplete').click(function() {
$('.task').show();
$('.task.completed').hide();
});
// Show only completed
$('#showCompleted').click(function() {
$('.task').hide();
$('.task.completed').show();
});
// Show all
$('#showAll').click(function() {
$('.task').show();
});
// Mark checked as complete
$('#markComplete').click(function() {
$(':checkbox:checked').closest('.task')
.addClass('completed');
});
// Remove completed
$('#removeCompleted').click(function() {
$('.task.completed').fadeOut(function() {
$(this).remove();
});
});
});
</script>
</head>
<body>
<h1>Task Manager</h1>
<div class="task">
<input type="checkbox"> Buy groceries
</div>
<div class="task completed">
<input type="checkbox"> Pay bills
</div>
<div class="task">
<input type="checkbox"> Call dentist
</div>
<div class="task completed">
<input type="checkbox"> Submit report
</div>
<br>
<button id="showIncomplete">Show Incomplete</button>
<button id="showCompleted">Show Completed</button>
<button id="showAll">Show All</button>
<br><br>
<button id="markComplete">Mark Checked Complete</button>
<button id="removeCompleted">Remove Completed</button>
</body>
</html>
Performance Considerations
⚠️ Performance Tips:
- Cache selections: Store frequently used selectors in variables
- Be specific:
$('#myId p')is faster than$('p') - Use IDs when possible: ID selectors are the fastest
- Avoid universal selector:
$('*')is slow - Limit traversal depth: Don't traverse too many levels
Summary
In this lesson, you learned:
- Form selectors: :text, :checkbox, :checked, :enabled, etc.
- Content filters: :contains(), :empty, :parent, :has()
- Visibility filters: :visible and :hidden
- NOT selector :not() for excluding elements
- Traversal methods: parent(), children(), siblings(), find()
- Filtering methods: filter(), first(), last(), eq(), slice()
- Using .end() to return to previous selection
- Performance best practices for selectors
In the next lesson, we'll compare jQuery with modern Vanilla JavaScript!