728 B
728 B
title, type, language, tags, author, cover, dateModified
| title | type | language | tags | author | cover | dateModified | |
|---|---|---|---|---|---|---|---|
| Find closest anchor | snippet | javascript |
|
chalarangelo | clouds-n-mountains | 2021-04-22T08:45:39+03:00 |
Finds the anchor node closest to the given node, if any.
- Use a
forloop andNode.parentNodeto traverse the node tree upwards from the givennode. - Use
Node.nodeNameandString.prototype.toLowerCase()to check if any given node is an anchor ('a'). - If no matching node is found, return
null.
const findClosestAnchor = node => {
for (let n = node; n.parentNode; n = n.parentNode)
if (n.nodeName.toLowerCase() === 'a') return n;
return null;
};
findClosestAnchor(document.querySelector('a > span')); // a