ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software

jQuery notes [part 1]: jQuery overview, reasons to use and retrieving page content using jQuery selectors & filters

Updated on January 11, 2014

What is jQuery?

  • free, open JavaScript library
  • simplifies the task of creating highly responsive web-pages
  • works across modern browsers
  • abstracts away browser-specific features, allowing you to concentrate on design
  • focus on simplifying common scripting tasks: [1]getting & manipulating page content, [2] working with the modern browser event model, [3] adding sophisticated effects: image fades
  • most modern web development scenarios involve common patterns like the followings and jQuery makes these scenarios easy:
    1. page loads -> perform a bunch of page set-up
    2. event -> retrieve content from the page -> manipulate or animate the content -> put the content back in the page
  • jQuery provides a way to run code when the DOM of the page is ready

Benefits of jQuery

  • leverage existing CSS knowledge
  • works with sets of elements
  • performs multiple operation on a set of elements with one line of code (statement chaining)
    hides various browser quirks (so we can concentrate on the end result)
  • extensible (usable to use 3rd parties plugs or own writing plug-in)
    compatible with most modern browsers

jQuery versions

jQury comes in 2 versions:

  1. production: compressed and minified
  2. development

Simple example of jQuery

		<script type="text/javascript" src="../jquery-1.10.2.min.js"></script>
		<script type="text/javascript">
			$("document").ready(function() {
				alert("Hello jQuery");




jQuery selectors & filters

  • retrieve content form the document so that it can be manipulate using other functions
  • jQuery selectors: return an array of objects based on the selection criteria
  • jQuery filters: operate on a selector to further refine the results array that the selector returns

Note: this array

  • is not a set of DOM elements
  • is a collection of jQuery objects that provide a large number of predefined functions for further operating on the objects

find all named tagname elements
find all ID identifier elements
find all elements which has className attribute
find elements which have: type like tag & attribute like className
$("li.a"); $("ul .b");
find elements which have: tag element with ID of id and class attributes with className
find all elements on the page
		<script type="text/javascript" src="../jquery-1.10.2.min.js"></script>
		<script type="text/javascript">
			$("document").ready(function() {
		<style type="text/css">
			.a { color: Navy; }
			.b { color: Maroon; }


		<ul id="list1">
			<li class="a">	item 1	</li>
			<li class="a">	item 2	</li>
			<li class="b">	item 3	</li>
			<li class="b">	item 4	</li>
		<p class="a">	Paragraph 1		</p>
		<p id="para1">	Paragraph 2		</p>
		<p class="b">	Paragraph 3		</p>
		<p id="para4" lang="en-us">	Paragraph 4	</p>



jQuery selectors

You can simply select elements based on hierarchical relationships or on a series of common criteria.

selector, selector ...
choose all specified selectors
.class1 .class2
choose all with bot .class1 and .class2 applied
parent > child
choose child under parent
ancestor descendant
choose all descendant elements that are comtained within elements of type ancestor
prev + next
find all next taare are after prev element
prev ~ siblings
find all sibling elements tahta come after prev and match the siblings selector


$("p").css("border", "1px dotted blue");

More examples (shorten)

$("p")		// choose all p
$(".a")		// choose all a class
$("#list1")	// choose all list1 id
$("p.b") 	// choose all b class p
$("p, li.b")	// choose all p & b class list
$("ul li.b")    // choose all b class list in ul
$("ul + p") 	// choose p next to ul
$("#list1 ~ p") //

jQuery filters

  • works with selectors to provide even more fine-grained control over how elements are selected in the document
  • categories: 6 categories
  1. basic: basic filtering (getting 1st, last, even, odd items, position, index)
  2. content: filters based on the content (whether an element contains particular string)
  3. visibility: filters using the visibility setting of each element as test
  4. attribute: filters based on attributes
  5. child: choose elements based on the relationship with parent element
  6. form: specialized filters on form element

choose only 1st element
choose only last element
choose only even-numbered element
choose only odd-numbered element
choose element: index = n
choose element: index > n
choose element: index < n
choose header elements (h1, h2 ..)
choose animated elements
choose that don't match the selector


$("p:first").css("border", "1px dotted blue");

More examples (shorten)

$("p:first")		// choose first p
$("p:last")		// choose last p
$("p:even")		// choose even p
$("p:odd")		// choose odd p
$(".a:first")		// choose a class 1st element
$(".b:even")		// choose b class even element 
$("p:gt(1)") 		// choose p with index >1
$("p:not(p:eq(2))")	// choose except p of index=2

Attribute flters

  • filter results of a selector statement based on attribute content

selected resultset elements are based on the specified attribute
selected resultset elements are based on [1] the specified attribute & [2] the given value of the attribute
includes elements in the result set only if the have hte specified attribute and it doesn't have the given value
includes elements that have the specified attribute and it starts with the specified value
inlcudes elements that have the specified attribute and it ends with the specified value
includes elements that have the speicfied attribute and it contatins the specified value
includes elements that match all of the specified attribute filters


$("p[class]").css("border", "1px dotted blue");	

More examples (shorten)

$("p[class]")	 			// choose the p which has class attribute
$("p[id=para1]") 			// choose the p which has i attr & attr has value para1
$("p[id^=para]")			// choose the p which has class attr & attr starts with para
$("p[id^=para][lang*=en-]")	// choose the p which has class attr & attr starts with para and en-1

Content filters

  • examine the content of the selected elements or their visibility property to determine whether they should be included or excluded from the final set.

content filter
filtesr based on the text string
filters to only include empty elements
filters based on the specified selector type elements
matches all elements that are parents


$("p:contains(3)").css("border", "1px dotted blue");
visibility filter
filters only the visible emements
filters only the hidden emements

Child filters

  • filters by examining the relationship each element has its parent element

child filter
matches elements at index. equation means Xn+M(2n, 3n+1)
match elements who are the first child of their parent
match elements who are the last child of their parent
match elements who are the only child of their parent


$("p:contains(3)").css("border", "3px solid red");

More examples (shorten)

$("p:contains(3)") 			// choose p which contains text string 3
$(":contains(3)")	 		// choose all elements which contains text string 3
$("p:parent") 				// choose all p which are parent
$("ul:has(li[class=a])")	// choose all ul which has class a list
$("ul li:nth-child(3)")		// choose 3rd index list item for the ul
$("ul li:last-child")		// choose last child item for the ul
$("ul li:nth-child(2n)")

Form selectors

  • deals with form elements
  • works like other selectors but start with a colon (:)
  • for additional formatting use: checked, selected, enabled

Sample form code


		<h1> Student Information Form </h1>
		<form action="" method="post">
			<table class="style1">
						<td class="style2"> First Name</td>			<td><input id="FirstName" type="text" /></td>
						<td class="style2"> Last Name</td>			<td><input id="LastName" type="text" />	</td>
						<td class="style2"> Disabled Element</td>	<td><input id="Text1" type="text" disabled="disabled"/>	</td>
						<td class="style2"> Gender</td>				<td><input id="Male" type="radio" checked="checked"/> M
																		<input id="Female" type="radio" />				  F </td>
						<td class="style2"> Department </td>
							<input id="Checkbox1" type="checkbox" checked="checked"/>		<label for="Checkbox1">CSE</label>		<br />
							<input id="Checkbox2" type="checkbox" />						<label for="Checkbox1">EEE</label>		<br />
							<input id="Checkbox3" type="checkbox" checked="checked"/>		<label for="Checkbox1">MCE</label>
						<td class="style2"> Comments:</td>
						<td><textarea id="Comments" cols="40" name="S1" rows="5"> </textarea></td>
						<td class="style2"> Profile picture</td>		<td><input id="File1" type="file" /></td>
						<td class="style2"> &nbsp;</td>
						<td> &nbsp;</td>
						<td class="style2"> &nbsp;</td>
							<input id="Submit1" type="submit" 	value="SUBMIT" />
							<input id="Reset1"	type="reset" 	value="RESET" />


Output of the sample code

Description (finds all ... elements)
nput, select, textarea, button elements
radio button

Form filters

Description (Matches all form elements that are...)
checked [radiobuttons, checkboxes]


$("form :input").before("Input: "); // insert "Text" before each input element
$("form :text").before("Text: ");
$("form :input").css("border", "3px solid red");
$("form :text").css("border", "3px solid red");
$("form :text:enabled").css("border", "3px solid red");
$("form :checked").css("border", "3px solid red");
$("form :checkbox:checked").css("border", "3px solid red");

Detail examples (jQuery part)

		<script type="text/javascript" src="../jquery-1.3.2.js"></script>
		<script type="text/javascript">
			$("document").ready(function() {
				$("form :input").before("INPUT_:");
				$("form :text").before("TEXT_:");
				$("form :text:enabled").before("ENABLE_:");
				$("form :text:disabled").before("DISABLE_:");
				$("form :checked").after("CHECKED_:");
				$("form :input").css("border", "1px solid blue");
				$("form :text").css("border", "1px solid blue");
				$("form :text:enabled").css("border", "1px solid blue");
				$("form :checked").css("border", "1px solid blue");
				$("form :checkbox:checked").css("border", "1px solid blue");
		<style type="text/css">
			.style1 { width: 800px;	}
			.style2 { width: 600px;	}

Sample output of the above code

Traversing document information

  • traverse the information returned from a document easily

Function / Property
size(), length
number of elements in the jQuery result set
returns an array of all matched DOM elements (used only if you use DOM instead of built-in jQuery functions)
access a single matched DOM element at a specified index in the method set
searches for descendent elements that match the specified expression
execute a function within the context of every matched element
//length and size() of a result set
var numberOfParagraphTags = $("p").length;
alert("Number of <p> elements: " + numberOfParagraphTags);  

// use the get() and get(index) to retrieve DOM elements
var DOM_elements = $("li").get();
var numberOfDOM_elements = DOM_elements.length;
alert("Number of <li> elements: " + numberOfDOM_elements);

// use the find function
$("ul").find("li.b").css("border", "3px solid red");

// use the each function
var leftmargin = 0;
var border = 3;
$("p").each(function() {
	$(this).css("border", border+"px solid red");
    $(this).css("margin-left", leftmargin);
    border += 5;
    leftmargin += 10;

jQuery statement chaining

  • chain multiple functions together to perform several operations in one line of code
  • example: $(selector) .function1() .function(2) .function3()

//get all links with attribute names 'href' & if the href ends with pdf: add a image icon
$("li a[href$=.pdf]").after("<img src='../images/pdf.gif'   align='absbottom' />");
$("li a[href$]").after("<img src='../images/email.gif' align='absbottom' />");


<a href="someurl.html"> 		Link #1 		</a>
<a name="#anchor1"> 			Amed Anchor Link</a>
<a href="someurl.html">			Link #2			</a>
<a href="someurl.pdf">			Link #3			</a>
<a href="">	Email Link		</a>


    0 of 8192 characters used
    Post Comment

    No comments yet.