8

A Complete Guide To jQuery – Learning The Basics

I recently bought the jQuery Cookbook by O'Reilly, and it is extremely useful and very informative. I wanted to share some of the things I've learned from it, and go over some stuff that you might not know about jQuery. I have taken some notes while reading the book and will share and talk about them in this post....
A Complete Guide To jQuery – Learning The Basics

First things first

The reasons you should use jQuery are because it's fast, easy to code, easy to learn, fully documented, and there's a huge community full of developers and users of jQuery with an enormous repository of plugins and and endless supply of tutorials available all over the internet. There's many more reasons to use it but I'm not here to sell it to you now am I.

Get to know the jQuery API!

This is important, as I am finding out more and more. You need to learn and know all you can about the jQuery API. Read about it, study it, memorize it, love it, even sleep with and dream about it... it's your best friend.

jQuery API Reference

The documentation on jQuery.com is wonderful and jQuery is fully documented. If you understand how the API works you'll be much better off. I admit that I don't really understand it at all, but I am learning, and someday will be able to explain it more in depth. If you are a visual learner like me, you can try using Visual jQuery to gain a better understanding of it. Use the menu to navigate, or use the search form to find something more specific. VisualjQuery.com is based on jQuery 1.2.6, but it is a good tool to start getting a handle on things.

Including the jQuery Library into a Page

So you want to include jQuery into a web page huh? Well you have a couple options for doing/

  1. Use the Google-hosted content delivery network (CDN) to include the latest version.
  2. Use your own copy of the jQuery that you can download from jQuery.com and host it on your server.
  3. Or just use WordPress!

Google-hosted jQuery

Many people including myself, would highly recommend using the latest version hosted on Google's content delivery network, using either the minified or nonminified version. You can learn more about the Google AJAX Libraries API here. Even jQuery.com uses the Google hosted version! I don't blame them, or anyone else who does for that matter. It is the fastest, most stable, reliable, and globally available copy of jQuery, so there are many benefits to using it. It gets cached whenever someone visits a page that has it included so it won't have to re-load every time since it is already available. Plus you don't have to worry about it once you add the script to your theme. To include it in your site, just add this to the footer.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script>

Use your version of jQuery

If you don't want to use the Google hosted copy of jQuery for whatever reason, you can download your own to host on your server. You may want to get a customized version from jQueryUI.com or, maybe your using it without an internet connection so you need it on your local machine. Maybe you just hate Google and think they are trying to take over the internet and eventually the world, and have a panic attack every time the release something new.

Whatever your reasons may be, this option allows you to use your own version of jQuery. Go here to find out about downloading jQuery. Once you have downloaded it add this code to your footer, changing PATH_TO_JQUERY so it points to the file.

<script src="PATH_TO_JQUERY" language="javascript"></script>

Just use WordPress, it rules!

If you are a WordPress user, and are running a WordPress blog or site of some kind then you're all set. WordPress comes packaged with jQuery, Prototype, MooTools, and JSON, all of which work straight out of the box after WordPress is installed. However, WordPress does not include the latest version of jQuery which currently is 1.4.2. As far as I know, WordPress 2.9.2 still uses the jQuery 1.3.2 version, if I am wrong let me know. If you would like to change it to use the latest you can add this code to your functions.php file in your theme.

// use latest version of jQuery in WordPress by default 1.4.x
if( !is_admin()){
   wp_deregister_script('jquery');
   wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"), false, '');
   wp_enqueue_script('jquery');
}

Executing jQuery/JavaScript after DOM loads

If you want to run a jQuery script that is coded after the DOM has loaded but before complete page load, you can use the ready() event handler method. It is jQuery's replacement for using the JavaScript core window.onload event and you can use it over and over as much as you want. The ready() method is passed a single parameter, a function, that has the JavaScript code that should be executed once the Document Object Model (DOM) is ready to be traversed and manipulated.

Tip: It is recommended that you include it after your CSS stylesheet is included, or any style declarations or classes you may want to jQuery access to be sure that all element properties will be properly defined before any jQuery or JavaScript is executed by the ready() event.

You are only able to use the ready() method when embedding jQuery in the <head> of a page. To avoid using the ready() method you can embed jQuery() in the <body> of the page.

Another option is to use the shortcut $ alias without worrying about creating conflicts instead of (jQuery) or ready().

Loading jQuery in the footer

The reason I say to add jQuery to your footer is because modern optimization techniques have declared pages to load faster when included at the end of a parsed page. The browser will load everything else in before it loads the JavaScript. It isn't absolutely necessary to add it to the footer, and you can choose to load it in the <head> if you want, it's just not really necessary to either.

Selecting DOM elements using selectors

Now that you have jQuery added to your page, you want to use it right? With jQuery you can select elements from the DOM using CSS selectors and custom selectors using the jQuery() or the $() alias. For example, the following code samples will select some elements in an HTML page.

// selects all <a> elements
jQuery ('a')

// selects all <li> elements
jQuery ('li')

// selects all <div> elements
jQuery ('div')

There is a much easier way to select these elements as this is way a little redundant and unnecessary. You can select all of them simply by typing this.

// selects all <a>, <li>, within <div> elements
jQuery('a li div')

Isn't that better? You can use this in so many ways some of which I'll go over below. Another method you can use to select elements is by their CSS class or ID. For example.

// selects the <div> with the #header ID and each <li> element within it
jQuery ('#header div li')

You can probably see how useful this can be for selecting elements on a page and manipulating them. So what if you wanted to filter a set of elements that you want to manipulate?

Filtering a wrapper set of elements

There is a function built into jQuery called the .filter() method which allows you to filter find and reduce a wrapped set of DOM elements by finding new ones, including all child elements of the current set. This code will get all <a> elements that have a class name of .external.

// <a> with class .external
jQuery('a').filter('.external')

When .filter() is used with an anonymous function $(this), this refers to the DOM elements in wrapper set. Here is an example code which checks to see if each element has a class value .hasClass() of .external, and if it does then keep it.

jQuery('a').filter(function() {
	return $(this).hasClass('external');
});

Keep in mind that these are just examples, and not necessarily the way such things should be done. It's just to show how it can be used.

Finding descendant/children elements within the current set

You can use the .children() method in jQuery to select all child elements of a previously selected element in a set. Meaning, you can select each <li> element of each <ul> element on a page. A more practical thing to do is this:

// select each <a> that is a child of #sidebar
jQuery ('#sidebar').children('a')

Another way is to use the jQuery method .find() which creates a new wrapper based on a context of the current set finding parent and child elements within the wrapper set.

This next snippet will find all <em> tags that are wrapped in <p> tags.

// find all <em> within all <p> elements
jQuery('p').find('em')

An easier way of doing this would be

jQuery('p em')

Note: Keep this in mind when working with these last two jQuery methods:

  • .filter() can only operate on the current set of elements
  • .find() can operate and select the children of the current set

Returning prior selection before destroying the current set

The .end() method is used to return the previous selected elements, and then destroys them so you can start over with no prior destructive methods used. Basically, an empty set is returned.

Destructive methods - any operation that changes the set of matched elements.

Some other destructive methods are:

add()
andSelf()
children()
closes()
filter()
find()
map()
next()
nextAll()
not()
parent()
parents()
prev()
prevAll()
siblings()
slice()
clone()
appendTo()
prependTo()
insertBefore()
insertAfter()
replaceAll()

Including the previous selection in the current selection

By using the .andSelf() method you can include a prior selection with current selection. But it is only added into the current set and prior set, not ALL prior sets.

jQuery('div').find('p').andSelf().css('border', '1px solid #993300');

Traversing the DOM based on your context

If you want to traverse the DOM based on your current context so you can get a new set of DOM elements use the :eq() index custom selector. This creates the context, and selects the specific element in a set. For example:

jQuery('li:eq(1)').next() 	// selects the 3rd li
jQuery('li:eq(1)').prev() 	// selects the 1st li
jQuery('li:eq(1)').parent() // selects the parent ul
jQuery('li:eq(1)').parent().children() //selects the parent and children - same as jQuery('li')
jQuery('li:eq(1)').nextAll() // selects everything after 2nd li
jQuery('li:eq(1)').prevAll() // selects everything before 2nd li

Each of these traversing methods create a new wrapper set. You can use end() to return to the previous set. In JavaScript, the index of an element is zero-based, meaning 0 is the first item in a wrapper. So by selecting 1, you are selecting the 2nd element in a set.

jQuery('li:eq(1)').parent().children(':last') // selects the last li

For more information on this and other ways to traverse the DOM using jQuery here is a complete list of Traversing methods in jQuery.

Creating, Operating, Inserting DOM elements

So maybe you want to select and create some DOM elements, perform an operation and insert the result into a page. The following jQuery code creates an HTML element, and creates the DOM element on the fly, then injects it into the page.

// find all <p><a> elements with the word jQuery inside
jQuery('<p><a>jQuery</a></p>').find('a')
	.attr('href', 'http://www.jquery.com') // add the href with an http value
	.end().appendTo('body'); // destroy the selection and add it to the <body>

That's pretty cool right? This is starting to get interesting, for those still reading this...

Some other manipulation methods() are:

  • .append()
  • .prepend()
  • .prependTo()
  • .after()
  • .before()
  • .insertAfter()
  • .insertBefore()
  • .wrap()
  • .wrapAll()
  • .wrapInner()

Removing DOM elements

Sometimes you want to remove things from the DOM, and to do that you can use the .remove() method which is used to remove a selected set of elements and their children from the DOM.

$('a').remove();
$('a').remove('.remove'); // removes only elements with the CSS class .remove

Using .remove() basically does just that. It removes elements from the DOM, not the jQuery wrapper set, and could be re-added to DOM also removes all event handlers and interanlly cached data that the elements may have had

Replacing DOM elements

If you want to replace an element in the DOM the replaceWith() method can be used to select DOM elements and replace them.

jQuery('li.remove').replaceWith('<li>removed</li>'); // li and children class .removed replaced
jQuery('li.remove').replaceAll('<li>removed</li>'); // all li and children are removed

Cloning DOM elements

You can use the clone() method to copy elements.

jQuery('ul').clone().appendTo('body');

This will clone the <li> elements that have a click event, insert them and all elements attached to them into an empty <ul>, then remove the cloned <ul>

jQuery('ul#a li') // select the ul elements with id 'a' and select the 'li' elements inside
.click(function() { alert('list item clicked') }) // attach a click even to each li
.parent().clone(true) // Traverse the DOM by selecting the parent ul, and clone it
.find('li') // within cloned elements change to only li within ul clone
.appendTo('#b') // take selected li and place them in cloned ul with ID of 'b'
.end() // return to the previous set selection which was the cloned ul
.end().remove(); // return the the previous selected set, the original ul, and remove the original ul

Getting, setting, removing

The attr() method is used for getting and setting values.

jQuery('a').attr('href','http://jquery.com').attr('href')
jQuery('a').attr('href':'http://jquery.com','title':'jquery.com').attr('href') // sets the title
jQuery('a').removeAttr('title')

Some other methods you can use to get, set, or remove values are:

  • addClass() - Updates the class attribute value with new class/value along with any classes that were set already
  • hasClass() - Checks the value of the class attribute for a specific class.
  • removeClass() - Removes a unique class from the class attribute while keeping and values set already
  • toggleClass() - Adds the specified class if it is not present; removes the specified class if its present.

Getting and setting HTML content

Use the html() method to get and set chunks of HTML elements or DOM structures.

jQuery('p').html('<strong>This is some HTML in a p tag</strong>');

Note: The html() method is not available for XML documents, but is for XHTML.

Getting and setting text content

You can use the text() method can get and set text elements.

jQuery('p').text('This is some text in a p tag');

Using the $ Alias without creating global conflicts

Create an anonymous self-invoking function that we pass the jQuery object to, then use $ character as a parameter pointer to the jQuery object (use $ to point to what we are passing through the function)

(fucntion($){ // function to create private scope with $ parameter
	// private scope and using $ without worry of conflict
})(jQuery); // invoke nameless function and pass it the jQuery object

This passes a global reference to jQuery to a function that creates a private scope. Without doing this we risk the possibility of no other scripts included use use the $ character.

For more information about jQuery noConflict click here.

That just about wraps up the basics of jQuery. I wrote this as a helper for those just starting out with jQuery, and I realize my note-taking skills could use some work. If you are unsure about anything here, or found something that doesn't quite make sense, please let me know, I wrote this early in the morning and may have missed some parts.

Shortlink:

Get automatic updates! Subscribe to Our RSS Feed or Get Email Updates sent straight to your inbox!

About the Author

Jared is from Boston working as a web and graphic designer. Also owns the design blog Tweeaks.com, and has designed many other websites powered by Wordpress including the New2WP theme.

Level: Noob

User Comments

( ADD YOURS )

  1. kudos for trying to do this, but unfortunately the text is FULL of MAJOR errors


  2. I have updated the post, I realized it wasn't as "complete" as I thought. If you still find errors please let me know.


  3. dude...

    // selects all <a>, , and elements
    jQuery('a li div')

    no it doesn't... it selects all DIVs that are inside LIs that are inside As

    // selects the with the #header ID and each element within it
    jQuery ('#div li')

    no it doesn't, it selects all LIs that are inside ANY element with id="DIV"... and it especially does NOT select the containing "div" (or #div)

    // <a> with class .external
    jQuery('a').filter('.external')

    extremely silly example as there's no reason not to just say jQuery('a.external') which would be way faster... maybe if you had said jQuery('a').css('border', '1px solid red').filter('.external').css('border', '1px solid blue') that would've made more sense

    etc...


  4. Thank you for the nice post, but I have a question, why appendTo() is considered as destructive operation since it doesn't create new set. It just only add the current selected set to the code?


  5. Thanks for the tutorial. I'm a jquery noob trying to pick it up as I go along.


  6. you could helped me to implement Jquery in my academic project. thanks for the Jquery tutorial.
    Techie Salsan recently posted..Difference between Lcd and Plasma TV


  7. very nice jquery tutorial, thanks for sharing !

  1. Avatar

    Your Name
    February 4


    CommentLuv badge