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();
The first
deepestis the variablebody, which is a jQuery object. Later, when you assign deepest tothis, it is a regular DOM element, which has noattrfunction.You have a bigger problem –
thisis 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 toeach. You want to pass the function itself to each.jsFiddle demo