views:

37

answers:

1

This question is a bit of a two-parter. First, the title question. Here's what I've got:

// Report all of the parents
$(this).parents().each(function(i){

    // Collect the parts in a var
    var $crumb = '';

    // Get the tag name of the parent
    $crumb += "<span class='tagName'>"+this.tagName+"</span>";

    // And finally, report it
    $breadcrumbs.prepend($crumb);

});

Unfortunately, this doesn't include the actual element itself, only the parents. Is there any way of saying something like "this and parents"?

Now, the second question. If I were unable to add to the stack, how would I separate the guts of that function into another function, while retaining the "this" ability of it? Would it be something like:

// Function to report the findings
function crumble(e){

    // Collect the parts in a var
    var $crumb = '';

    // Get the tag name of the parent
    $crumb += "<span class='tagName'>"+this.tagName+"</span>";

    // And finally, report it
    $breadcrumbs.prepend($crumb);

};
$(this).parents().each(crumble());

Thanks in advance for your time!

+6  A: 

For the first question, you can use the .andSelf method:

$(this).parents().andSelf().each(function () {
  // ..
});

You have to note something, the $crumb variable is locally-scoped, so it will initialize in every iteration of you each loop.

For your second question, yes, you can define a function that does the job of the each callback, you just have to pass a reference to it, and not invoke it (remove the parens):

$(this).parents().each(crumble);
CMS
Nice! Thanks. Could you recommend a reference to invoking / not invoking functions (like crumble)? I'd like to learn more =)
Matrym
Oh, here's an interesting little fact about your solution too. It reverses the order of the stack! Easy enough to resolve with reverse(), or append (instead of prepend).
Matrym