Skip to main content
Finds and renders all Mermaid diagrams in the document. This method processes elements matching a selector (default: .mermaid), converting their text content into SVG diagrams.

Signature

async function run(options?: RunOptions): Promise<void>

Parameters

options
RunOptions
Optional configuration for the run operation.

Return value

Promise<void> - Resolves when all diagrams have been rendered.

Behavior

  • Processes elements sequentially, not in parallel
  • Sets data-processed="true" attribute on rendered elements
  • Skips elements that already have data-processed attribute
  • Generates unique IDs for diagrams using format mermaid-{n}
  • Decodes HTML entities and normalizes whitespace in diagram definitions
  • Replaces element’s innerHTML with rendered SVG
  • Throws first error encountered unless suppressErrors is true

Examples

Basic usage

import mermaid from 'mermaid';

mermaid.initialize({ theme: 'dark' });
await mermaid.run();

Custom selector

// Render all elements with class "diagram"
await mermaid.run({
  querySelector: '.diagram'
});

Specific nodes

// Render only specific elements
const nodes = document.querySelectorAll('.custom-mermaid');
await mermaid.run({
  nodes: nodes
});

With callback

// Track rendered diagrams
await mermaid.run({
  postRenderCallback: (id) => {
    console.log(`Rendered diagram: ${id}`);
    // Perform additional operations
  }
});

Error suppression

// Continue rendering even if some diagrams fail
await mermaid.run({
  suppressErrors: true
});

Complete example with HTML

<!DOCTYPE html>
<html>
<head>
  <script type="module">
    import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs';
    
    mermaid.initialize({ theme: 'default' });
    
    document.addEventListener('DOMContentLoaded', async () => {
      await mermaid.run();
    });
  </script>
</head>
<body>
  <div class="mermaid">
    graph TD
      A[Start] --> B[Process]
      B --> C[End]
  </div>
  
  <div class="mermaid">
    sequenceDiagram
      Alice->>Bob: Hello
      Bob->>Alice: Hi!
  </div>
</body>
</html>

Usage notes

  • Can be called multiple times; already-processed diagrams are skipped
  • Use initialize() before calling run() to configure Mermaid
  • Elements must be in the DOM before calling run()
  • The method processes innerHTML, so ensure content is properly escaped
  • Diagram text is dedented and trimmed before processing
If suppressErrors is false (default), the first error will stop processing and throw. Use suppressErrors: true to render all valid diagrams even if some fail.
  • initialize() - Configure Mermaid before rendering
  • render() - Render a single diagram programmatically
  • parse() - Validate diagram syntax without rendering

Build docs developers (and LLMs) love