简体   繁体   中英

My recursive function isn't returning anything

I'm trying to select a the parent form element of an input. The form element isn't necessarily the direct parent node. Currently this outputs "undefined" to my log.

var anInputElement = document.querySelector(...);
var formElement = getFormElement(anInputElement);
console.log(formElement);

function getFormElement(elem) {
  //if we've traversed as high as the `body` node then
  //we aint finding the `form` node
  if(elem.nodeName.toLowerCase() !== 'body') {
    var parent = elem.parentNode;
    if(parent.nodeName.toLowerCase() === 'form') {
      return parent;
    } else {
      getFormElement(parent);
    }
  } else {
    return false;
  }
}

Why am I getting undefined in my console log?

not just

getFormElement(parent);

but

return getFormElement(parent);

and simplified, just for fun:

function getFormElement(elem) {
  if(elem.nodeName.toLowerCase() !== 'body') {
    var parent = elem.parentNode;
    return parent.nodeName.toLowerCase() === 'form' ? parent : getFormElement(parent);
  }

  return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM