简体   繁体   English

element.tagName 返回未定义

[英]element.tagName returns undefined

I have to write a function that will return the closest relative (parent or child) with the given tagName.我必须编写一个函数,该函数将使用给定的 tagName 返回最近的亲戚(父母或孩子)。 Here is my code:这是我的代码:

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

The console is returning the name of the tag, but the return value is undefined .控制台正在返回标签的名称,但返回值是undefined

You are trying to read .tagName twice.您正在尝试读取.tagName两次。

In your closestRelative function, you are returning closestChild.tagName.toString() .在您的closestRelative函数中,您将返回closestChild.tagName.toString() Then in your test code, you're doing relative && relative.tagName , trying to read it again.然后在您的测试代码中,您正在执行relative && relative.tagName ,尝试再次读取它。 Since the function already returned a string, reading .tagName results in undefined .由于函数已经返回一个字符串,读取.tagName导致undefined

You might want to remove the .tagName in the last console.log , or change closestRelative to return the tag itself ( closestChild ) instead of the tag name.您可能希望删除最后一个console.log中的.tagName ,或更改closestRelative以返回标签本身 ( closestChild ) 而不是标签名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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