Skip to content

Instantly share code, notes, and snippets.

@gabemeola
Last active August 2, 2018 20:02
Show Gist options
  • Save gabemeola/bcc289472d0c5dcbc422256a6e83f72c to your computer and use it in GitHub Desktop.
Save gabemeola/bcc289472d0c5dcbc422256a6e83f72c to your computer and use it in GitHub Desktop.
Searches for a comment in target document
/**
* Searches for a comment in target document
*
* @author Gabe M
* @param {string} commentText - Comment text to search for
* @param {Node} [target=document] - Parent target to search through
* @return {Array<Node>}
*/
function getCommentsByText(commentText, target = document) {
const nodeList = [];
const treeWalker = document.createTreeWalker(
target,
NodeFilter.SHOW_COMMENT,
{
acceptNode(node) {
return node.nodeValue === commentText
? NodeFilter.FILTER_ACCEPT
: NodeFilter.FILTER_REJECT;
},
}
);
// Walk Tree
while (treeWalker.nextNode()) nodeList.push(treeWalker.currentNode);
return nodeList;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment