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;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments