0

我必须编写一个函数,该函数将返回具有给定 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.

4

1 回答 1

0

您正在尝试阅读.tagName两次。

在您的closestRelative函数中,您正在返回closestChild.tagName.toString(). 然后在您的测试代码中,您正在relative && relative.tagName尝试再次阅读它。由于该函数已返回一个字符串,因此读取.tagName结果为undefined.

您可能希望删除.tagName最后一个console.log,或更改closestRelative为返回标签本身 ( closestChild) 而不是标签名称。

于 2021-07-24T18:42:14.853 回答