$(document).ready(function() {
// Example 1: Select by Element Tag
var h1Element = $('h1');
h1Element.text('Hello, jQuery!');
// Example 2: Select by Class
var paragraph = $('.paragraph');
paragraph.text('This is an updated paragraph.');
// Example 3: Select by ID
var listItem2 = $('#item2');
listItem2.text('Modified Item 2');
// Example 4: Select by Attribute
var listItems = $('li[data-index="1"]');
listItems.css('color', 'blue');
// Example 5: Select by Multiple Selectors
$('h1, p, li').css('font-weight', 'bold');
// Example 6: Select by Descendants
var allListItems = $('ul li');
allListItems.css('background-color', 'lightgray');
// Example 7: Select by First and Last
$('li:first').css('color', 'red');
$('li:last').css('color', 'green');
// Example 8: Select by Even and Odd Index
$('li:even').css('background-color', 'yellow');
$('li:odd').css('background-color', 'orange');
// Example 9: Select by Child
$('ul > li').css('border', '1px solid black');
});
In this example, we have different ways of selecting elements using various selectors:
Select by Element Tag: $('h1')
Select by Class: $('.paragraph')
Select by ID: $('#item2')
Select by Attribute: $('li[data-index="1"]')
Select by Multiple Selectors: $('h1, p, li')
Select by Descendants: $('ul li')
Select by First and Last: $('li:first') and $('li:last'
)
Select by Even and Odd Index: $('li:even') and $('li:odd')
Select by Child: $('ul > li')