ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

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

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

	<body>

	</body>

</html>

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

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

	<body>

		<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>
		</ul>
		
		<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>

	</body>

</html>

jQuery selectors

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

selector
description
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

Example

$("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

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

Example

$("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

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

Example:

$("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
description
:contatins(text)
filtesr based on the text string
:empty
filters to only include empty elements
:has(selector)
filters based on the specified selector type elements
:parent
matches all elements that are parents

Example

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

Child filters

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

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

Example

$("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

<html>
	<head>
	</head>
	<body>

		<h1> Student Information Form </h1>
		<form action="" method="post">
			<table class="style1">
				<tbody>
					<tr>
						<td class="style2"> First Name</td>			<td><input id="FirstName" type="text" /></td>
					</tr>
					<tr>
						<td class="style2"> Last Name</td>			<td><input id="LastName" type="text" />	</td>
					</tr>
					<tr>
						<td class="style2"> Disabled Element</td>	<td><input id="Text1" type="text" disabled="disabled"/>	</td>
					</tr>
					<tr>
						<td class="style2"> Gender</td>				<td><input id="Male" type="radio" checked="checked"/> M
																		<input id="Female" type="radio" />				  F </td>
					</tr>
					<tr>
						<td class="style2"> Department </td>
						<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>
					</tr>
					<tr>
						<td class="style2"> Comments:</td>
						<td><textarea id="Comments" cols="40" name="S1" rows="5"> </textarea></td>
					</tr>
					<tr>
						<td class="style2"> Profile picture</td>		<td><input id="File1" type="file" /></td>
					</tr>
					<tr>
						<td class="style2"> &nbsp;</td>
						<td> &nbsp;</td>
					</tr>
					<tr>
						<td class="style2"> &nbsp;</td>
						<td>
							<input id="Submit1" type="submit" 	value="SUBMIT" />
							<input id="Reset1"	type="reset" 	value="RESET" />
						</td>
					</tr>
				</tbody>
			</table>

		</form>
	</body>
</html>

Output of the sample code

Selector
Description (finds all ... elements)
:input
nput, select, textarea, button elements
:text
text
:password
password
:radio
radio button
:checkbox
checkbox
:submit
submit
:reset
reset
:image
image
:button
button
:file
upload

Form filters

Selector
Description (Matches all form elements that are...)
:enabled
enabled
:desabled
desabled
:checked
checked [radiobuttons, checkboxes]
:selected
selecte

Examples

$("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");
			});
		</script>
		<style type="text/css">
			.style1 { width: 800px;	}
			.style2 { width: 600px;	}
		</style>

Sample output of the above code

Traversing document information

  • traverse the information returned from a document easily

Function / Property
Description
size(), length
number of elements in the jQuery result set
get()
returns an array of all matched DOM elements (used only if you use DOM instead of built-in jQuery functions)
get(index)
access a single matched DOM element at a specified index in the method set
find(expression)
searches for descendent elements that match the specified expression
each(data)
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);
        
alert($("li").get(0));

// 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$=.com]").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="mailto:joe@joe.com">	Email Link		</a>

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)