我必须编写一个函数,该函数将返回具有给定 tagName 的最近亲属(父母或孩子)。这是我的代码:
function closestRelative(parent, relativeName) {
var closestParent = parent.parentNode.closest(relativeName);
var childrenElements = parent.children;
var closetChild;
for(var i=0; i<childrenElements.length; i++) {
if(childrenElements[i].tagName === relativeName.toUpperCase()){
closestChild = childrenElements[i];
}
}
console.log(closestChild.tagName);
//if(closestParent) return closestParent.tagName;
//if(closestChild) return closestChild.tagName;
//return null;
return closestChild.tagName.toString();
}
// Example case
document.body.innerHTML =
'<James>' +
'<Dave></Dave>' +
'<Mike></Mike>' +
'<Sarah></Sarah>' +
'</James>';
let parent = document.getElementsByTagName('James')[0];
let relative = closestRelative(parent, 'Mike');
console.log(relative && relative.tagName); // prints MIKE
控制台正在返回标签的名称,但返回值为undefined
.