Skip to content

Instantly share code, notes, and snippets.

@john-yuan
Created January 9, 2019 01:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save john-yuan/926bf84ac128aaa3177b980d0e556090 to your computer and use it in GitHub Desktop.
Save john-yuan/926bf84ac128aaa3177b980d0e556090 to your computer and use it in GitHub Desktop.
Get the first Node that has the className in the path from the fromNode to the toNode.
/**
* Get the first `Node` that has the `className` in the path from the `fromNode` to the `toNode`
*
* @param {Node} fromNode The `Node` at which the search begins
* @param {string} className The class name to test (only single className)
* @param {Node} [toNode] The optional `Node` at which the search ends
* @returns {Node} Returns the `Node` we found, if not found, `null` is returned
*/
var closestNode = function (fromNode, className, toNode) {
var node = null;
var nodeClassName = '';
if (typeof className !== 'string') {
if (className === null || className === undefined) {
className = '';
} else {
className = '' + className;
}
}
className = ' ' + className.replace(/^\s+|\s+$/g, '') + ' ';
while (true) {
if (!fromNode) {
break;
}
nodeClassName = fromNode.className;
if (nodeClassName === null || nodeClassName === undefined) {
nodeClassName = '';
}
nodeClassName = ' ' + nodeClassName + ' ';
if (nodeClassName.indexOf(className) > -1) {
node = fromNode;
break;
} else if (fromNode === toNode) {
break;
} else {
fromNode = fromNode.parentNode;
}
}
return node;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment