.end() makes jQuery DOM traversal beautiful

This is my new favorite jQuery trick. I just learned it this year and have mentioned it in enough code reviews to decide it’s worth sharing.

When manipulating the DOM with jQuery, you often see code that looks something like:

$("#container").show();
$("#container .error").hide();
$("#container .zoo").css("background-color", "white");
$("#container .zoo .monkeys").empty();
$("#container .zoo .title").text("The zoo is empty");
$("#container .zoo input").val("");
$("#container .zoo").animate({height: 250});

…or, if somebody gets concerned about performance, they might try to reduce DOM lookups:

var container = $("#container");
container.show();
container.find(".error").hide();
container.find(".zoo").css("background-color", "white");
...

…and so on. Odds are, when you’re manipulating a single element like container, you’ll probably be doing something to nearby elements in the next few lines of code.


Readers of this blog, meet Emma. Emma, meet the three readers of this blog.

Enter .end(), newlines, indentation, and chaining. When you have one jQuery chain going and modify it with, say, .find(), you’re actually pushing the new chained set of elements onto a stack. .end() pops the current jQuery chain off the stack, which lets you do stuff like this:

$("#container")
    .show()
    .find(".error")
        .hide()
        .end()
    .find(".zoo")
        .css("background-color", "white")
        .find(".monkeys")
            .empty()
            .end()
        .find(".title")
            .text("The zoo is empty")
            .end()
        .find("input")
            .val("")
            .end()
        .animate({height: 250});

It’s easy to read, because the indentation is significant and matches up with DOM nesting levels. It gets rid of unnecessary DOM lookups. But most importantly for me, it feels natural to indent in and out as I write the code, using small additional selectors to step deeper into the DOM and .end() to find my way back out.

I’ve been destroying my old, ugly var’s left and right with this trick. I hope it helps somebody else.

Comments 12/26/11 — 10:52am Permalink
 
  1. bjk5 posted this