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.
You are trying to read
.tagNametwice.In your
closestRelativefunction, you are returningclosestChild.tagName.toString(). Then in your test code, you're doingrelative && relative.tagName, trying to read it again. Since the function already returned a string, reading.tagNameresults inundefined.You might want to remove the
.tagNamein the lastconsole.log, or changeclosestRelativeto return the tag itself (closestChild) instead of the tag name.