🎯 jQuery Attribute & Form Selectors
Finding Elements by Their Secret Labels
🏷️ The Story: Elements Wear Name Tags!
Imagine you’re at a huge party with hundreds of guests. How do you find your friend?
- Some guests wear name tags (attributes!)
- Some have special badges (data attributes!)
- Some are filling out sign-up forms (form elements!)
- Some are busy, some are waiting (form states!)
jQuery is like having magic glasses that can instantly spot anyone based on their tag, badge, or what they’re doing. Let’s learn to use these glasses!
1️⃣ Attribute Selector Basics
What’s an Attribute?
Think of HTML attributes as labels stuck on boxes. Each box (element) can have labels like:
<a href="https://google.com">Link</a>
<input type="text" name="email">
<img src="cat.jpg" alt="A cute cat">
The href, type, name, src, alt – these are all attributes!
The Magic Syntax
To find elements with a specific attribute:
// Find ALL elements that have a "href" attribute
$("[href]")
// Find ALL inputs that have a "name" attribute
$("[name]")
// Find ALL elements with an "id" attribute
$("[id]")
The square brackets [ ] are your attribute detector!
Real Example
<a href="#">Home</a>
<a href="#">About</a>
<span>No link here</span>
$("[href]").css("color", "blue");
// Only the <a> tags turn blue!
// The <span> stays normal.
2️⃣ Attribute Value Selectors
Finding elements that have an attribute is nice, but what about finding exact matches?
Exact Match: =
// Find input where type EXACTLY equals "text"
$('input[type="text"]')
// Find link where href EXACTLY equals "#home"
$('a[href="#home"]')
Contains Word: ~=
Matches when the attribute value contains a whole word (separated by spaces):
<p class="warning big bold">Alert!</p>
$('[class~="big"]') // ✅ Matches!
$('[class~="bi"]') // ❌ Doesn't match
Starts With: ^=
// Find links starting with "https"
$('a[href^="https"]')
// Find inputs with names starting with "user"
$('input[name^="user"]')
Ends With: $=
// Find images ending with ".png"
$('img[src$=".png"]')
// Find links ending with ".pdf"
$('a[href$=".pdf"]')
Contains Substring: *=
// Find any link containing "google"
$('a[href*="google"]')
// Find inputs containing "mail" anywhere
$('input[name*="mail"]')
Quick Reference Chart
| Selector | Meaning | Example |
|---|---|---|
[attr="val"] |
Exactly equals | [type="text"] |
[attr~="val"] |
Contains word | [class~="active"] |
[attr^="val"] |
Starts with | [href^="https"] |
[attr$="val"] |
Ends with | [src$=".jpg"] |
[attr*="val"] |
Contains anywhere | [name*="user"] |
3️⃣ Multiple Attribute Selector
Sometimes you need to be extra specific. Like finding someone who’s:
- Wearing a red shirt AND
- Has a name tag AND
- Carrying a bag
Stack Them Together!
// Input that is BOTH type="text" AND has name="email"
$('input[type="text"][name="email"]')
// Link that starts with "https" AND ends with ".pdf"
$('a[href^="https"][href$=".pdf"]')
// Element with class AND data attribute
$('[class="btn"][data-action="submit"]')
Real World Example
<input type="text" name="username">
<input type="text" name="email">
<input type="password" name="email">
// Only gets the TEXT input named "email"
$('input[type="text"][name="email"]')
4️⃣ Selecting by Data Attributes
What Are Data Attributes?
HTML5 gave us custom pockets to store information:
<button data-user-id="123" data-action="delete">
Delete User
</button>
<div data-theme="dark" data-size="large">
Content
</div>
Any attribute starting with data- is a data attribute!
Selecting Data Attributes
Use the same square bracket syntax:
// Find elements with data-user-id attribute
$('[data-user-id]')
// Find elements where data-theme is "dark"
$('[data-theme="dark"]')
// Find buttons with data-action starting with "del"
$('button[data-action^="del"]')
Pro Tip: Reading Data Values
// Get the value of a data attribute
var userId = $('[data-user-id]').data('user-id');
// Returns: 123
// Or use attr()
var theme = $('[data-theme]').attr('data-theme');
// Returns: "dark"
5️⃣ Form Element Selectors
Forms have special guest passes in jQuery! These are shortcuts for common form elements.
The Magic Shortcuts
| Selector | What It Finds | Same As |
|---|---|---|
:input |
ALL form elements | inputs, textareas, selects, buttons |
:text |
Text inputs | input[type="text"] |
:password |
Password inputs | input[type="password"] |
:radio |
Radio buttons | input[type="radio"] |
:checkbox |
Checkboxes | input[type="checkbox"] |
:submit |
Submit buttons | input[type="submit"] |
:button |
Button elements | button, input[type="button"] |
:file |
File uploads | input[type="file"] |
Examples in Action
<form>
<input type="text" name="user">
<input type="password" name="pass">
<input type="checkbox" name="remember">
<button type="submit">Login</button>
</form>
// Get all text inputs
$(":text")
// Get all checkboxes
$(":checkbox")
// Get EVERYTHING in forms
$(":input") // Gets ALL 4 elements!
Important Note! 🚨
Always add a parent selector for better performance:
// ❌ Slower - searches entire page
$(":text")
// ✅ Faster - searches only in #myForm
$("#myForm :text")
$("form :checkbox")
6️⃣ Form State Selectors
Elements can be in different moods or states. jQuery can detect these too!
The State Detectors
| Selector | What It Finds |
|---|---|
:enabled |
Elements that CAN be used |
:disabled |
Elements that are grayed out |
:checked |
Checked checkboxes/radios |
:selected |
Selected dropdown options |
:focus |
Currently focused element |
Examples
<input type="text" disabled>
<input type="text">
<input type="checkbox" checked>
<select>
<option>One</option>
<option selected>Two</option>
</select>
// Find enabled inputs (not disabled)
$(":enabled")
// Find disabled inputs
$(":disabled")
// Find checked checkboxes
$(":checked")
// Find selected option in dropdown
$("option:selected")
Real World: Form Validation
// Highlight empty required fields
$('input:enabled').each(function() {
if ($(this).val() === '') {
$(this).css('border', '2px solid red');
}
});
// Get checked checkbox values
$(':checked').each(function() {
console.log($(this).val());
});
🎮 Putting It All Together
Let’s build a user search form:
<form id="userForm">
<input type="text" name="search"
data-validate="required">
<input type="email" name="email"
data-validate="email">
<input type="checkbox" name="active"
data-filter="status">
<button type="submit" disabled>
Search
</button>
</form>
Power Combo Selectors
// Text inputs with validation
$('#userForm input[type="text"][data-validate]')
// All filter checkboxes
$('[data-filter]:checkbox')
// Enable submit when form is valid
$('#userForm :submit').prop('disabled', false);
// Get all checked filter values
$('[data-filter]:checked').each(function() {
console.log($(this).attr('name'));
});
🧠 Memory Tricks
The Bracket Family [ ]
[attr] → Has it?
[attr="x"] → Exactly x?
[attr^="x"] → Starts with x?
[attr$="x"] → Ends with x?
[attr*="x"] → Contains x?
The Colon Crew :
:text, :password, :checkbox → Form types
:enabled, :disabled → Can use it?
:checked, :selected → Is it on?
🚀 You Did It!
You now have X-ray vision for HTML! You can find:
✅ Elements by their attributes ✅ Elements by attribute values (exact, starts, ends, contains) ✅ Elements with multiple attributes ✅ Elements by data attributes ✅ Form elements by type ✅ Form elements by state
Go practice! Try selecting elements on any webpage using your browser console. Just type $('[href]') and watch the magic! 🎉
