3

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!

Matrym
  • 16,643
  • 33
  • 95
  • 140

1 Answers1

7

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);
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • Nice! Thanks. Could you recommend a reference to invoking / not invoking functions (like crumble)? I'd like to learn more =) – Matrym Apr 01 '10 at 05:25
  • 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 Apr 01 '10 at 05:27