This is part of an on-going beginners introduction to jQuery web programming series. Part 1 covered the jQuery basics of how to include it in your project, and selectors. In part 2, we’ll continue with basic usage as we look at some methods you can perform on those DOM elements, and some more language fundamentals.
If you recall from lesson 1, this is the basic structure of a DOM manipulation in jQuery. DOM manipulation isn’t the only thing you can do with jQuery of course, but it’s the easiest place to start from and the most common, so that’s why we chose it.
To quickly recap, the selector part of this statement allows you to use CSS-like element names, classes, or IDs in order to locate parts of the DOM. For example, to grab all the <div> with a class name of .hidden, we would use:
The second part of this equation is the method to perform on these DIVs once we’ve found them (if they exist at all; or they may only be one “matching” item). Remember, jQuery will only ever return one element for ID selections, since IDs should refer to unique items. If you’re going to have more than one of something, it must be defined as a class in CSS.
On to methods then; what can you do with elements of the DOM anyway?
First off, I introduced you to the .css method last time so that you could use it for testing. The format is simple:
Anything definable by CSS can therefore be adjusted by jQuery – colors, transparency, location, size – to name but a few. The change is immediate.
If you’d rather animate the CSS changes, then I’ve got great news for you; there’s also a method called .animate(). It’s a little more complex though:
As an example:
At this point, you might be wondering what the curly braces are for; they’re called an “object literal”, and are typically used to create a list of property:value pairs, kind of like an indexed array if you’re coming from other languages. You’ll use them a lot in jQuery, so I’ll say this again – get used to checking properly for closed brackets and braces!
Check out this page for lots of working examples of the animate method.
As well as manipulating the CSS properties of something, you can adjust the contents of it with the .text(), .html(), and .val() methods too (val is for the contents of form elements). These methods act as both setters and getters; if you don’t specify a value, they will get the current value. If you do specify a value, they will replace the current value.
Here are some quick examples:
Get the current value of the name field in the comment form and assign it to a variable comment_name:
var commenter_name = $(#comment-form #name).val();
Set the value of <span class=’name’> to the value grabbed from commenter_name:
Then we have a vast selection of methods for cloning, moving around, inserting or deleting parts of the DOM. Your imagination is the limit, really.
$('div#content p:nth-child(3n)').after('<img src="ad.jpg"/>');
Breaking that down, we’ve asked jQuery to:
- Find the div with an ID of “content”
- Find the p’s contained within that div
- Filter to every 3rd p using nth-child pseudo selector (more on that here)
- Insert an arbitrary img after each matching element
I can’t possibly list all the methods here and nor would you want to read that. The point is, there’s a method for doing pretty much whatever you can think of when it comes to manipulation, so check the API for one you can use.
Also, bear in mind that there might be more than one way to do something. If for example you can’t narrow down the correct object to insertAfter(), perhaps think about finding the next child down and using insertBefore() instead.
Lastly today, let’s have a quick word about method chaining, basically just because it’s awesome. First, let’s consider the following lines of code:
$('nav#menu').fadeIn('fast'); $('nav#menu').addClass('beingShown'); $('nav#menu').css('margin-right','10px');
That sounds reasonable enough, right? But you can do the same in just one line:
That does exactly the same thing, and is called method chaining. Since nearly all jQuery methods return a jQuery object themselves, each one can feed into the next. This means less code – which is always a good thing – but it actually also runs faster.
Why? Well, each time you invoke the basic jQuery $ command and selector, you’re asking it to search through the DOM tree looking for a matching element. When you chain methods, you don’t need too keep referring back to the DOM, because it knows where they are now, and can perform the method instantly.
That’s it for today, and I think we’ve probably covered quite a lot. You should now be armed with the ability to perform some pretty heavy DOM manipulations, so have a go, chain your methods together and make a real mess of the page. For now, you’ll want to place your scripts in the footer in order to give the rest of the page time to load. Next week we’ll tackle the issue of making jQuery do things only when everything has loaded correctly with events, and the curious case of anonymous functions.