Iterating Over a DOM Collection with the jQuery.each Method

jQuery

jQuery Logo - each method
jQuery makes it super easy to get a reference to a collection of DOM elements. The jquery.each method allows you to execute a function against each one of the elements in the collection.

Solving problems is one of jQuery’s best qualities, and the beauty of the jQuery.each method is that it solves a very common problem: how to iterate a collection of DOM elements. Now in order to work through this task, one might be inclined to set up a for-loop. This approach is not at all wrong; in fact, on some levels it makes perfect sense. The thing is, in tackling it this way you run into a few avoidable problems. First, there is a lot of boilerplate code. In other words, to set up the for-loop you would need a counter variable, which we’ll call “i”. And since we might want to iterate a collection of DOM elements more than once, we’d need to make the “i” variable private, which means using a function to create private or “local” scope. Also, 80% of our for-loop would be repeated code. So, you get the picture… our problems are mounting, and they most assuredly are avoidable. So, here’s where the beauty of the jQuery.each method comes into play: it provides abstraction for creating a for-loop. This means that we need only provide the collection and a callback method that we wanted executed for each iteration of the loop.

The jQuery.each method is the go-to tool when you need to iterate a collection of DOM elements. Let’s say you have a bunch of elements in the page. Maybe that bunch is “every <a> tag” or “every <li> inside of the <ul> with the class sales”, or each <div> element that is a child of <div class=”members”>.

Here is how you would create a reference to each of those collections

jQuery will return a collection with one or more members. But how do you iterate over that collection and “do something” to each one? You can accomplish this by chaining the .each() method to the return value, and of course, pass a callback to that method.

jQuery.each Method – Basic Syntax

In the above example, where you see “selector”, that represents a CSS-like query such as “p” or “#some-id p img”, etc., that you would pass to jQuery. Now you can see that we have passed a callback function to the each() method. And inside of that callback, we would take care of any tasks that are specific to the elements over which we are currently iterating.

So, for an example, we will create a click-event handler for each <li> inside of a <ul>. Here is the markup we will work with:

With that markup in mind, consider the following code:

Example # 1

Notice that in Example # 1 we use $(this). Now just in case you are not familiar with this pattern, $(this) equals “the current element”, and it happens twice in our code. The first instance of $(this) on line # 2 refers to the element that is currently being iterated over (i.e. the current “UL LI”). The second $(this) on line # 3 represents the element that was just clicked. This is because we want to change the color of the element that was just clicked to red.

From a pseudocode perspective, here is what we have done:1- For each <li> that is inside of a <ul>, add a click event handler
2 – In the click-event handler, we say “If you click me, make my text red”

Example # 2

In Example # 2, we change the logic a bit so that only an <li> with the class “workday” is returned in the collection, which means that the “saturday” and “sunday” <li> elements do have a click event handler assigned.

Here is the JsFiddle link for this example: http://jsfiddle.net/WHkkA/. Simply remove the .workday class from the CSS selector to see Example # 1 work.

Summary

The jQuery .each() method is used to iterate over the members of a jQuery collection. There is definitely more fun stuff that can be done with this method, but this is just a very basic overview of what the method does and how to use it.

Important Note: Try not to confuse this with the jQuery.each() method. That is a similar concept, but more of a general-purpose iteration method that is a static method call to the jQuery object, not a method of a jQuery collection.

How to Use the jQuery replaceWith Method

jQuery

JavaScript LogoThe replaceWith() method provides a way to completely remove an element and put another in its place

Most of the time, jQuery is used to add click event handlers to DOM elements, and there’s nothing wrong with this. In fact, jQuery is so helpful in this context, it’s hard to argue against using it for your event handling / delegation. But just be aware… there are other tasks that come up, and some of them can get rather messy. One example is replacing one DOM element with another. Now this may sound simple, but with vanilla JavaScript, this kind of work can get pretty tedious. Normally, I recommend learning how to do things with vanilla JavaScript that you would want to do with jQuery, but there are times when this kind of wheel reinvention becomes a bad idea.

So, this is where the jQuery replaceWith() method comes in; it allows you to chop out one piece of the page and replace it with another. You simply specify the original section of the DOM as well as the new chunk, and then jQuery takes care of all the work. And what makes this method so helpful is the expressive syntax; on a high-level, it’s a simple as A.replaceWith(B). You really do have to thank the folks from jQuery, for packing a great deal of abstraction into this one method. If you don’t believe me, go ahead and try this yourself using just vanilla JavaScript. I think you’ll find that it’s pretty tedious.

Example # 1

In example # 1, we have attached an event handler to the element with the id: “foo”. When clicked, that element is removed from the page, and replaced with a piece of markup defined in a string. Yes, it’s that easy, and there are certainly more interesting things you can do with this jQuery method.

Summary

Replacing one section of the page with another piece of markup is quite easy with the jQuery replaceWith() method. The syntax is very straight-forward and if you are already familiar with jQuery, there are quite a few possibilities.

Helpful links for the jQuery replaceWith method

http://api.jquery.com/replaceWith/

http://www.w3schools.com/jquery/html_replacewith.asp

http://stackoverflow.com/questions/730916/whats-the-difference-between-jquerys-replacewith-and-html

http://stackoverflow.com/questions/5248721/jquery-replacewith-fade-animate

Two Alternatives to the jQuery Document Ready Function for JavaScript

jQuery

jQuery Logo

There are two alternatives to document ready that are a bit easier to type

Most JavaScript programmers are familiar with jQuery’s document ready function. There is no doubt that it is a very helpful way to wrap your JavaScript with a cross-browser compatible function that will not run until the document has achieved a “ready” state. While the syntax is fairly simple, there are two slightly less verbose alternatives to the exact same functionality.

Example # 1

 

In Example # 1, we have the standard syntax for the jQuery document ready function.

Example # 2

 

In Example # 2, we omit the “document / ready” portion of the equation, and simply insert our function in the following expression $().

Example # 3

In Example # 3, we chain a jQuery ready() function to the return value of the jQuery object: $().ready(). So, when the jQuery object is ready, so is our code.

Summary

There is no doubt that the jQuery document .ready() function is super-useful. There is however, more than one way to invoke this functionality.

Helpful links for the jQuery document .ready() function

http://api.jquery.com/ready/

http://docs.jquery.com/Tutorials:Introducing_$(document).ready()

http://rpheath.com/posts/403-jquery-shorthand-for-document-ready

http://think2loud.com/653-jquery-document-ready-howto/

 

 

 

jQuery Under the Hood with Paul Irish

jQuery

jQuery Logo

If you’ve never poked around inside of jQuery, you should. Paul’s videos are a great way to get started

I decided to ring in the new year with two of Paul Irish’s videos that I had book-marked, but had not gotten around to viewing: 10 Things I Learned from the jQuery Source and 11 More Things I Learned from the jQuery Source.

In these two videos, you have Paul’s screen, so that you can follow his code, and a small sub-screen of his head while he talks, so that you can follow his hilarious commentary and thought pattern. My only complaint: there is so much good stuff here to dive into that it takes an hour to watch a 30 minute video because of the constant temptation to hit “pause” and then fire up JSFiddle and play around with the concepts that he discusses.

10 Things I Learned from the jQuery Source – YouTube

In general, exploring the un-minified version of jQuery is just plain ol’ good sense. There is a tendency to simply use jQuery and treat it as some magic black box that “just works, and works great…” But the fact of the matter is, there is only one thing going on inside of that giant self-executing function: JavaScript. That is it.

Everything that jQuery does for you, you could have done for yourself… but, jQuery is better, stronger and faster than the average bear. Fair enough. But, that does not mean that we should not lift up the hood, poke around and learn from the code inside… because what is going on in there is pretty dammed cool. The jQuery folks do things in some very interesting ways and there are tons (and I do mean tons) of neat stuff to learn from.

11 More Things I Learned from the jQuery Source – YouTube

Highlights of Paul’s videos include a brief discussion of jQuery’s “no conflict” feature,  his decision to hijack the .ready() method, and a hilarious discussion of how jQuery detects the presence of Internet Explorer (and the technique used is just so brilliantly creative that I had to once again pause the video, copy the code while squinting at the YouTube page, and try it in notepad myself… it just works).

If you are a JavaScript developer, you owe it to yourself to check out these videos. Paul Irish is pretty funny, and he is one of the top web developers out there. This combination makes all of his videos a pleasure to watch (and most importantly, to learn from).

Writing More Expressive and Readable jQuery Code with Method Chaining

jQuery

jQuery LogoYou can chain jQuery methods in a way that makes your code more readable, and allows you to be more expressive in the way that you traverse and manipulate DOM elements

Most of us are introduced to jQuery via the following scenario: when the user clicks an element, you want something to happen to that element. You Google the code, you copy the code, you edit the code so that it matches your DOM elements, it works, you are hooked, you add “jQuery” to your resume. An oft-told tale.

But, what about when the user clicks an element, and we want numerous thing to happen to elements that are in the neighborhood? Perhaps we want the parent element to turn blue, and then we want the <a> inside of the <span> that is a sibling to change it’s href attribute….etc. Sure, we can do all this using jQuery methods such as parent(), find() and end(). But the code starts to get a little verbose. One way in which we can write this kind of code in a slightly more elegant manner is by chaining method calls together. It makes the code more expressive and a little easier to read.

Example # 1

In example # 1, we query a specific selector, change its background color, use the parent() method to find the element’s parent, and then change the parent element’s background color to red. Pretty simple stuff. But, this code can be written better.

Example # 2 A

Example # 2 B

In example # 2 A, because $(this) returns a jQuery object, we can avoid further queries by simply “chaining” subsequent method calls. Chaining refers to using the return value of one method to kick off another method call, and so on. The concept is like that of a “chain reaction” in that one return value drives the call to the next method, and so on. In example # 2 B, we have the exact same code, but we break each of the “chained” methods calls to a new line, which makes the code even more expressive and easier to follow (comments have been added as well). JavaScript does not care about this white space, so you are free to organize your code in any way you like, which allows you to “express” your thoughts, or “logic” in a way that you feel works best.

This next example is a bit long, but what I wanted to accomplish was:

  • Provide full page markup so that you can copy the entire code, paste it into notepad and run the file, or use jsfiddle.net
  • Create an example where we chain methods together that walk up and then down the DOM, mutating multiple elements, without ever having to create another query

Example # 3

 

In example # 3, we use the jQuery parent(), find(), and end() methods to move up and then back down the DOM, mutating elements along the way, without ever having to write a second query. The next example is the exact same code, but heavily commented, to make it easier to follow-along.

Example # 4

 

In example # 4, we have the exact same code as example # 3, with comments added.

Summary

When a jQuery method returns a jQuery object, you can take advantage of that behavior by “chaning” subsequent method calls to the return value of the previous method. When using this approach, you can execute multiple DOM statements from the result of one query. The end result is code that is more expressive and easier to read.

Helpful links for chaining jQuery methods

http://ejohn.org/blog/ultra-chaining-with-jquery/

http://paulirish.com/2008/sequentially-chain-your-callbacks-in-jquery-two-ways/

http://forum.jquery.com/topic/jquery-method-chaining-returned-object-something-i-don-t-get

http://www.jquery-tutorial.net/introduction/method-chaining/