Is there any reason that this:
function find_parent_p(x){
daddy = jQuery(x).parent();
if(daddy.attr("tagName").toLowerCase() == 'p'){
console.log(daddy,"result");
return (daddy);
} else {
find_parent_p(daddy);
}
}
jQuery(document).ready(function($){
$('img').each(function(){
next = find_parent_p($(this));
})
});
would return a jQuery object in the console (expected behaviour), where as the following returns Undefined All I am doing is moving the call to console.log outside the function, and after the call to it:
function find_parent_p(x){
daddy = jQuery(x).parent();
if(daddy.attr("tagName").toLowerCase() == 'p'){
return (daddy);
} else {
find_parent_p(daddy);
}
}
jQuery(document).ready(function($){
$('img').each(function(){
next = find_parent_p($(this));
console.log(next,"result");
})
});
You’re missing the
returnstatement in yourelsecondition. If your function recurses, then the top level call won’t return anything, and you’ll end up withundefined.