Traverse the DOM With jQuery

jquery

In web development and specifically with using the awesome jQuery library, traversing the information returned from a document is a very common task. jQuery makes this much easier for you with some great methods of the jQuery Object. There are a lot of ways to make your way around, but it makes sense to focus on the ones that are most used, and will be most useful to you. Let’s take a look at the ones we’ll be using frequently now.


Traversing the Document

Method Name

Use Case

size() or length Provides the total number of elements in the wrapped set
get() Returns the actual DOM elements rather than jQuery wrapped objects
get(index) Retrieve a single DOM element
find(expression) Finds elements that match the expression given
each(fn) A form of looping to allow a function to be executed on every matched element

Let’t talk about the use cases for each of the methods listed above. The first one is the size() method. When doing selections on the DOM with jQuery, it is often useful to find out how many objects were returned in the wrapped set. You may want to check the number of links on a given page. With this method, you can find that information out. In fact this simple snippet will tell you just that. $('a').size(); Other times your code may simply need to check if objects were returned or not and what steps may or may not come next based on this result. Again this method is what you would use that for. In addition to this method, you could simply use the length property as it provides the same exact information. In fact, when I’m reading data, this feels a bit more natural, $('a').length;

The get() and get(index) methods are used to get access directly to the DOM elements themselves. Remember, when we are doing selections in jQuery, what gets returned to us are the DOM elements that are wrapped inside a jQuery object. This is why it is typically referred to as the wrapped set. This is how those returned objects are able to have access to the many convenient methods that the jQuery library provides. If there is a use case where you simply just want to operate on actual native DOM elements themselves using native JavaScript, then this is when you can use get() or get(index) to accomplish this goal.

find() is used to search inside a matched element to find another element based on the expression provided to the method.

each() is great since it allows you to easily loop over the contents of the wrapped set and perform actions on them via functions. Most popular jQuery plugins use this method frequently.

Let’s whip up an example of using the each() method on our returned set. Here is the code, and we’ll just run it in firebug to keep it simple. You can follow along if you like.

jquery each

Cool! So how does this work? What happens here is first, we set a counter in the variable i. The next thing to do is to set up a theme array, and populate it with four different classes that we are going to use in the function that runs in our each() method. Now, we select all of the paragraph elements on the page and apply the each() method to the result. They way each() works is you specify an anonymous function inside of the each() method, or in other words, we pass an anonymous function to the each() method. Now, each() is going to loop over all of the elements in our wrapped set. In this case we have four paragraphs so what happens is, starting with the first iteration, we use the .addClass() method on the first element to assign a specific class name. How does this happen? It looks a little different than your typical loop structure than you may be used to. $(this) actually changes on each iteration. The first time through, it is referencing the first paragraph in our wrapped set. The second time through, it is referencing the second paragraph in our wrapped set, and so on. Since $(this) is a jQuery object, and *not* a raw DOM Element, we can enjoy access to any method jQuery makes available to us. In this case, we’re using the .addClass() method, but it could just as easily be any number of other methods in the jQuery library. On iteration one, $(this) is paragraph one, and i is at index 0. Therefore, when we run the .addClass() method on $(this), it applies the class of alert alert-info to this paragraph since that is the class that lives at index 0 of the theme array. On the next iteration, we are dealing with paragraph two. This time, the counter has been incremented so when we add the class, it is now alert alert-success that gets applied since that is the class that lives at index 1 of the theme array. This continues until all elements have been looped over. This is how we can make use of the .each() method, awesome!


Statement Chaining with jQuery

Statement chaining is an incredibly powerful feature of the jQuery library that allows you to link together multiple method calls on your result set in one single line of code. The format for this type of statement chaining looks like so.

$(selector).fn1().fn2().fn3();

The .fn1().fn2().fn3(); portion is the statement chain in this example. So what’s the big deal you ask? Well, if you return a bunch of elements with your selector, you can then apply a function to all of them and once complete apply another, and then another, all in a very compact style of syntax. It is worth noting that some of the JavaScript Gurus have expressed their opinions that this style may have been taken to an extreme in recent years, but it is still a useful tool in your jQuery toolkit. For a bit of a non sensical example, let’s look at the following code:

This introduces the concept of callbacks in jQuery in addition to the method chaining we are using. Notice in the code that we use the selector only once in the whole expression. We only reference the last paragraph on the page by using the $('p:last') selector. From there, it is simply a matter of applying different methods to that element in succession. Talking through the example helps to drive the point home. First, we grab the last paragraph element on the page. Then the alert alert-info class is added to the element via the .addClass() method. Now comes the first additional method that makes up our statement chain, .slideUp(). The .slideUp() method takes two arguments, and one is a callback so it is worth explaining. The first argument simply tells the .slideUp() method at what speed we would like the effect to happen at. In our case, we make it slow. The second option is a callback function, and it is really cool how this works. Since we can pass a function as an argument to another function in JavaScript, it makes these types of callbacks possible. The way the callback works is first, it waits for the function it is being passed to, to finish it’s execution. Once it is complete, the callback function will run. This is why when the paragraph slides up, it retains it’s original class and color until it has finished sliding. Once it stops, the anonymous callback function runs and triggers two things to happen. In true jQuery style, we are actually embedding a statement chain within a statement chain here! When the anonymous function runs, this line of code gets triggered:

Here, $(this) refers to the paragraph element that we originally captured. This is excellent, since we do not have to go through the overhead of selecting that element yet again. Using this convention, we can reduce the number of times we have to actually query the document, and just work with our elements as long as need be until they have reached the state we desire.

So what this line says is, “take that original paragraph element we have, remove the class we had assigned to it, the add a different class to it“. Very slick.

After that we add to the original statement chain by running the .slideDown() method, then the .fadeOut() method which also takes a callback function. Finally we run the final .fadeIn() method to finish the statement chain. This shows us two things, first that statement chaining is really cool and useful, and two, that you can see where people might take this style to an extreme, so certainly use this approach but keep it within reason 🙂

Once you have this small collection of methods mastered, visit the offical docs to learn about some additional traversing methods you might find useful.