npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

marked-attributes

v1.0.0

Published

Add custom HTML attributes to any marked token

Readme

marked-attributes

A marked.js extension that allows you to add custom HTML attributes (including CSS classes, data attributes, IDs, etc.) to tokens during the rendering process.

Why Use This?

  • Programmatic Control: Add attributes dynamically based on token properties or external conditions data—without modifying your markdown source
  • Dynamic Logic: Generate IDs from counters, add classes based on heading depth, inject tracking attributes conditionally
  • Simpler Than Custom Renderers: No need to override 20+ renderer methods manually; works automatically for all token types
  • Clean Markdown: Keep your markdown portable and readable without inline syntax like {.class #id} required

Installation

npm install marked-attributes

Basic Setup

import { marked } from 'marked'
import { markedAttributes } from 'marked-attributes'

// Enable attribute rendering
marked.use(markedAttributes())

// Now use marked as normal
const html = marked.parse('**bold text**')

Adding Attributes with walkTokens

The simplest way to add attributes is using marked's walkTokens hook:

import { marked } from 'marked'
import { markedAttributes } from 'marked-attributes'

marked.use(markedAttributes())

// Add unique IDs to all tokens
let idCounter = 0
marked.use({
  walkTokens(token) {
    token.attributes = {
      'data-token-id': `token-${++idCounter}`
    }
  }
})

const html = marked.parse('This is **bold** text')
<p data-token-id="token-1">This is <strong data-token-id="token-2">bold</strong> text</p>

TypeScript Support

Import and use the TokenWithAttributes for type assertion:

import { marked } from 'marked'
import { markedAttributes, type TokenWithAttributes } from 'marked-attributes'

marked.use(markedAttributes())

marked.use({
  walkTokens(token: TokenWithAttributes) {
    token.attributes = { 'class': 'my-class' }  // ✓ TypeScript recognizes .attributes
  }
})

Usage Examples

Dynamic Attributes Based on Token Properties

marked.use(markedAttributes())

let headingCounter = 0

marked.use({
  walkTokens(token) {
    // Dynamic IDs for headings
    if (token.type === 'heading') {
      headingCounter++
      token.attributes = {
        'id': `heading-${headingCounter}`,
        'class': `level-${token.depth}`,
        'data-level': token.depth.toString()
      }
    }

    // Add analytics tracking to external links only
    if (token.type === 'link' && token.href.startsWith('http')) {
      token.attributes = {
        'data-analytics-action': 'click',
        'data-analytics-label': token.href,
        'rel': 'noopener noreferrer',
        'target': '_blank'
      }
    }
  }
})

const html = marked.parse('# Title\n\nVisit [example](https://example.com)')

Output:

<h1 id="heading-1" class="level-1" data-level="1">Title</h1>
<a href="..." data-analytics-action="click" rel="noopener noreferrer" target="_blank">example</a>

Hierarchical Token IDs

Useful for contenteditable markdown editors to track cursor positions:

marked.use(markedAttributes())

const addHierarchicalIds = (tokens, prefix = '') => {
  tokens.forEach((token, index) => {
    const id = prefix ? `${prefix}.${index + 1}` : `${index + 1}`
    token.attributes = { 'data-token-id': id }

    if (token.tokens) {
      addHierarchicalIds(token.tokens, id)
    }
  })
}

const tokens = marked.lexer('This is **bold and _italic_** text')
addHierarchicalIds(tokens)
const html = marked.parser(tokens)

// Outputs hierarchical IDs like: 1, 1.1, 1.1.1, etc.

Use Cases

// CSS Styling: Custom classes for headings, blockquotes, code blocks
if (token.type === 'heading') token.attributes = { 'class': `heading-${token.depth}` }
if (token.type === 'blockquote') token.attributes = { 'class': 'callout-box' }

// Contenteditable Editors: Track cursor positions
token.attributes = { 'data-token-id': generateUniqueId() }

// E2E Testing: Stable test IDs
token.attributes = { 'data-testid': `${token.type}-${index}` }

// Analytics: Track interactions
if (token.type === 'link') token.attributes = { 'data-analytics-action': 'click' }

// Accessibility: ARIA attributes
if (token.type === 'heading') token.attributes = { 'aria-level': token.depth.toString() }

// Interactive Features: Data attributes for JS
token.attributes = { 'data-interactive': 'true', 'data-component': 'markdown-element' }

Credits

Wanting to implement post-render handlers and processes, and this helpful dicussion.