scythargon
scythargon

Reputation: 3491

JavaScript's strange behavior

If uncomment body.children().each(calc_deep(1)); then i get TypeError: Object [object Window] has no method 'attr' on the parseInt(deepest.attr('deep')) string, but without uncomment you can check in console that you can call deepest.attr('deep'). What is that?

    var deepest;
    var calc_deep = function(i)
    {
        $(this).attr('deep',i);
        if(i>parseInt(deepest.attr('deep')))
            deepest=this;
        $(this).children().each(calc_deep(i+1));
    }
    var find_deepest = function()
    {
         body=$('body').children().eq(0);         
         body.attr('deep',0);
         deepest=body;
         //body.children().each(calc_deep(1));
    }
    find_deepest();

Upvotes: 0

Views: 79

Answers (2)

Dennis
Dennis

Reputation: 32598

The first deepest is the variable body, which is a jQuery object. Later, when you assign deepest to this, it is a regular DOM element, which has no attr function.

You have a bigger problem - this is not pointing the element you think it is. Call $(this).children().each(calc_deep); without the argument to the function. To get the depth, just get it from the parent. You are calling the function calc_deep and passing the (non-existant) return value to each. You want to pass the function itself to each.

var deepest, index;
var calc_deep = function() {
    var $this = $(this); //cache jQuery this
    var i = $this.parent().data("deep") + 1;
    $this.data('deep', i);
    if (i > index) {
        deepest = $this;
        index = i;
    }
    $this.children().each(calc_deep);
}
var find_deepest = function() {
    body = $('body').children().eq(0);
    body.data('deep', 0);
    index = 0;
    deepest = body;
    body.children().each(calc_deep);
}
find_deepest();

jsFiddle demo

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

each takes a function for an argument, you are passing it undefined - because you are calling the function first and then its return value is what each() gets.

Use function() {calc_deep(1);} instead.

Upvotes: 4

Related Questions