Skip to content

Instantly share code, notes, and snippets.

@cododel
Created October 30, 2024 12:37
Show Gist options
  • Save cododel/99317c8ec4eb7b124e7aede9c8292b33 to your computer and use it in GitHub Desktop.
Save cododel/99317c8ec4eb7b124e7aede9c8292b33 to your computer and use it in GitHub Desktop.
JavaScript HTML Comment Selector class
class CommentSelector {
static comments = [];
static getAllCommentNodes() {
if (this.comments.length > 0) return this.comments;
const commentNodes = [];
const iterator = document.createNodeIterator(document, NodeFilter.SHOW_COMMENT, null, false);
let currentNode;
while ((currentNode = iterator.nextNode())) {
commentNodes.push(currentNode);
}
this.comments = commentNodes;
return commentNodes;
}
static selectByComment(cb) {
return this.getAllCommentNodes().find(cb);
}
static selectByCommentText(text) {
return this.selectByComment((comment) => comment.nodeValue.trim() === text);
}
static selectAllByTextIncludes(text) {
return this.getAllCommentNodes().filter((comment) => comment.nodeValue.includes(text));
}
static selectByTextIncludes(text) {
return this.getAllCommentNodes().find((comment) => comment.nodeValue.includes(text));
}
static cleanComments() {
this.comments = [];
}
}
@cododel
Copy link
Author

cododel commented Oct 30, 2024

Subscribe to my telegram channel, don’t miss new interesting solutions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment