Sunday, March 13, 2011

jQuery Fundamentals Part 2: Selection

This is the second part of a 5 part series on jQuery fundamentals. In this part, we will look at how to make HTML element selections using jQuery. The next part will focus on how to manipulate these selections. This easy method for selecting and manipulating the DOM is one of jQuery's most valuable strengths.

jQueryUI

Below is an example of a common jQuery statement followed by an explanation of each section of this jQuery statement. This first part of the “jQuery Fundamentals” will focus on the selection part of the statement below:








jQuery Object: Any jQuery action starts with the '$' character.  Starting a statement with the '$' character lets you know that you are working with a jQuery statement.  Alternatively, you may also replace the '$' character with the word 'jQuery' if you want your code to be more explicit.    

Element Selection: select an HTML element from the HTML document. This example selects an element with id = 'exampleDiv'.  We will go into more detail on how to make these selections shortly.

Action: After making a selection, you probably want to perform some action on the selection. This example adds a CSS class to the 'exampleDiv' selection.  There are many actions that jQuery is able to do.  Some of my favorites to use include .addClass, .html, .val, .append, and .ajax().  We will cover most of these in Part 3 of this series.

Parameters: If the jQuery method takes any parameters, they go here. This example adds the CSS class 'exampleClass' to the exampleDiv selection.

You can select your HTML elements in a number of different ways. You can select by CSS class, ID, element type, or any combination of the three.

Selection by Element:
/*
 * This statement selects all of the Div elements in an HTML document.
 */
$(“div”).AddClass(“exampleClass”)   


Selection by Class:
/*
 * This statement selects all HTML elements with a class of “exampleClass” 
 * attached to it, then adds some HTML. Note that selection by class requires 
 * a “.” prepended to the class name.
 */
$(“.exampleClass”).AddClass(“anotherExampleClass”) 


Selection by ID:
/*
 * This statement selects all HTML elements with an id of “exampleID”, then 
 * adds some HTML inside of the selected tags. Note that selection by ID 
 * requires a “#” prepended to the ID name.
 */
$(“#exampleID”).Html(“someHtml”) 

Selection by Combination:
/* 
 * This statement selects all HTML elements with an ID = 'exampleID', that 
 * also have the class = 'exampleClass' which are contained within Div tags.
 */
$(“div .exampleClass #exampleID”).AddClass(“exampleClass”) 


The next part of this series will be on how to manipulate the selections we have just learned how to make.


No comments:

Post a Comment