HTML Comment Selector | Cododel
CODODELDEV
EN / RU
Back to Deck
[utility]

HTML Comment Selector

SOURCE JavaScript
VERSION 1.0
AUTHOR Cododel

A JavaScript class for selecting DOM nodes based on HTML comment content. Perfect for scraping websites where developers left helpful comments, or for testing applications with comment-based markers.

Use Case

Many web applications (especially Angular, React, Vue) leave HTML comments in the DOM to mark data bindings or component boundaries. This class allows you to leverage those comments to locate elements:

// Select element by exact comment text
const regNumber = CommentSelector.selectByTextIncludes('collectionItem.regNumber').parentElement
.innerText
// Find all comments containing specific text
const dataComments = CommentSelector.selectAllByTextIncludes('{{')
// Clean cache when DOM changes
CommentSelector.cleanComments()

Real Example

On a page like https://goskatalog.ru/portal/#/collections?id=55029802:

  1. Open DevTools Console
  2. Paste the CommentSelector class code
  3. Use it to extract data:
const regNumber = CommentSelector.selectByTextIncludes('collectionItem.regNumber').parentElement
.innerText
console.log(regNumber) // Outputs the registration number

Features

  • Comment caching: Scans DOM once, caches results
  • Flexible search: Exact match or substring search
  • Filter support: Find one or find all
  • Simple API: Static methods, no instantiation needed
  • Fast: Uses native NodeIterator API

Source Code

CommentSelector.js

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 = []
}
}

API Reference

MethodDescription
getAllCommentNodes()Returns all HTML comment nodes (cached)
selectByComment(callback)Find comment using custom filter function
selectByCommentText(text)Find comment by exact text match
selectByTextIncludes(text)Find first comment containing text
selectAllByTextIncludes(text)Find all comments containing text
cleanComments()Clear cache (use after DOM changes)
[ ▲ 0 ]