A most common usage pattern for jQuery is to programmatically select (or grab) an element and then do something to it - usually add a listener or manipulate (change) it in some way
jQuery allows us to use css selectors to select elements:
// We can use css selectors to programmatically select elements
$('p'); // Element/Tag selector
$('.feature'); // Class selector
$('#checkout'); // ID selector
$('li strong'); // Descendant selector
$('em, i'); // Multiple selector
$('a[target="_blank"]'); // Attribute selector
$('p:nth-child(2)'); // Pseudo-class selector
Example #1
In the example above jQuery is used to listen for a .click() event on the #button
element and then call the completeItem()
function when that element is clicked
Inside the changeBackgroundColor
function, $("p")
selects the p element and uses the .toggleClass() method to dynamically toggle the class of .red-background
Example #2
In the example above jQuery is used to listen for a .click() event on the #mark-complete
element and then call the completeItem()
function when the element is clicked
Inside the completeItem
function, $("p.last-of-type")
selects the last p element and uses the .addClass() method to dynamically add a class to the element