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 event.target into a jQuery object -- which is as easy as $(event.target) -- 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)

<head>
        <script 
                src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" 
                type="text/javascript"
        ></script>
        <script>
                var Util = {};
                Util.logit = function(strToLog, strSource)    {
                        if (window.console)     {
                                console.log(strToLog);
                        }
                }
        </script>
</head>

<body>
    <div class="family">
        Mirror.  Razor.
        <div class="grandparentDiv">
            Grandparent
            <div class="parentDiv">
                Parent
                <div class="childDiv">
                    Child
                </div>
                <div class="siblingDiv">
                    Sibling
                </div>
            </div>
            <div class="uncleDiv">
                Uncle
                <div class="cousinDiv">
                    Cousin
                </div>
            </div>
        </div>
        <div class="greatUncleDiv">
            Great Uncle
        </div>
    </div>

    <script>
        $(".family").on("click", "div", function(event){
            // let's find our great uncle.
            var $family,
            $familyMember = $(event.target),
// http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/
            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
                .trim();

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

            event.stopPropagation(); // don't need all the ancestors firing off.
        });
    </script>                
</body>

Labels: ,