Today's fun topic to remember for later is traversing DOM with jQuery. I generally hate using the DOM as a stand-in for data -- if you're polling your DOM for input values, for instance, you're Doing It Wrong. But if you're traversing your GUI to change your GUI, well, I guess that's okay. Stupid to have a data store to mirror your doc's already existing object model. This is especially useful for dealing with events. So maybe you're listening to the focus event to see if some other widget related to that one should also be displayed. Wrap into a jQuery object -- which is as easy as $( -- and get moving.

So the two players in DOM traversal with jQuery are closest (to go up) and find (to go back down). Enjoy.

(as a jsFiddle here)

                var Util = {};
                Util.logit = function(strToLog, strSource)    {
                        if (window.console)     {

    <div class="family">
        Mirror.  Razor.
        <div class="grandparentDiv">
            <div class="parentDiv">
                <div class="childDiv">
                <div class="siblingDiv">
            <div class="uncleDiv">
                <div class="cousinDiv">
        <div class="greatUncleDiv">
            Great Uncle

        $(".family").on("click", "div", function(event){
            // let's find our great uncle.
            var $family,
            $familyMember = $(,
            strFamilyMemberText = $familyMember
                .clone()     //clone the element
                .children()  //select all the children
                .remove()    //remove all the children
                .end()       //again go back to selected element
                .text()     //get the text of element

            $family = $familyMember.closest(".family");
            alert(strFamilyMemberText + " found " 
                + $family.find(".greatUncleDiv").text().trim());

            event.stopPropagation(); // don't need all the ancestors firing off.

Labels: ,