element.tagName returns undefined

320 Views Asked by At

I have to write a function that will return the closest relative (parent or child) with the given 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.

1

There are 1 best solutions below

0
Kelvin Schoofs On

You are trying to read .tagName twice.

In your closestRelative function, you are returning closestChild.tagName.toString(). Then in your test code, you're doing relative && relative.tagName, trying to read it again. Since the function already returned a string, reading .tagName results in 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.