generateSelector (section-detection)

agentation · scraping, css-selector-generation, element-identification, dom-utility, dev-tools

Generates a unique CSS selector for a given DOM element, prioritizing semantic tags, IDs, meaningful classes, and falling back to nth-child paths.

export function generateSelector(el: HTMLElement): string {
  const tag = el.tagName.toLowerCase();

  // Unique semantic tags (usually only one nav, one footer, etc.)
  if (["nav", "header", "footer", "main"].includes(tag)) {
    // Check if it's unique
    if (document.querySelectorAll(tag).length === 1) {
      return tag;
    }
  }

  // ID selector
  if (el.id) {
    return `#${CSS.escape(el.id)}`;
  }

  // Tag + first meaningful class
  if (el.className && typeof el.className === "string") {
    const classes = el.className.split(/\s+/).filter(c => c.length > 0);
    // Find a class that isn't just a hash
    const meaningful = classes.find(c =>
      c.length > 2 && !/^[a-zA-Z0-9]{6,}$/.test(c) && !/^[a-z]{1,2}$/.test(c)
    );
    if (meaningful) {
      const selector = `${tag}.$

... (truncated -- full source via MCP)

See the full source, get the GitHub permalink, and search 40K more like it.

Get a free API key