JQuery

Jquery Selectors

jQuery Selectors: The Basics

What Are jQuery Selectors?

  • Selectors let you find HTML elements so you can manipulate or interact with them using jQuery.

  • They work very similarly to CSS selectors but with extra power.


Common jQuery Selectors

Selector Description Example
$('#id') Select element by ID $('#header')
$('.class') Select elements by class $('.menu-item')
$('tag') Select elements by tag name $('p')
$('*') Select all elements $('*')
$('parent > child') Select direct children $('ul > li')
$('selector:first') Select first matched element $('li:first')
$('selector:last') Select last matched element $('li:last')
$('selector:eq(index)') Select element at specific index $('li:eq(2)') (third item)

Attribute Selectors

Selector Description Example
$('[attr]') Select elements with attribute $('[disabled]')
$('[attr="value"]') Select elements with exact attribute value $('[type="checkbox"]')
$('[attr^="start"]') Select elements where attribute starts with value $('[name^="user"]')
$('[attr$="end"]') Select elements where attribute ends with value $('[src$=".jpg"]')
$('[attr*="contain"]') Select elements where attribute contains value $('[class*="button"]')

Examples

js
// Select all paragraphs and change text color
$('p').css('color', 'blue');

// Hide all elements with class "hide-me"
$('.hide-me').hide();

// Select the element with ID "main" and add a border
$('#main').css('border', '2px solid red');

// Select all checked checkboxes
$('input[type="checkbox"]:checked').each(function() {
console.log($(this).val());
});


Bonus: Filters and Pseudo-Selectors

Selector Description Example
:visible Select visible elements $('div:visible')
:hidden Select hidden elements $('input:hidden')
:animated Select elements currently animating $('div:animated')
:contains("text") Select elements containing text $('p:contains("Hello")')
:input Select input, textarea, select, button $(':input')

Summary

jQuery selectors make it super easy to grab exactly the elements you want, then manipulate or attach events to them.

Leave a Reply

Your email address will not be published. Required fields are marked *