Browser-specific functions for highlighting HTML elements and integrating with web pages. Provides automatic discovery and highlighting of code blocks in the DOM.
Automatically finds and highlights all code blocks on the current page.
/**
* Auto-highlights all <pre><code> elements on the page
* Uses CSS selector from configuration (default: 'pre code')
* Respects noHighlightRe configuration for skipping elements
*/
function highlightAll(): void;Usage Examples:
import hljs from 'highlight.js';
// Highlight all code blocks after page load
document.addEventListener('DOMContentLoaded', () => {
hljs.highlightAll();
});
// Re-highlight after dynamic content is added
function addCodeBlock(codeText, language) {
const pre = document.createElement('pre');
const code = document.createElement('code');
code.className = `language-${language}`;
code.textContent = codeText;
pre.appendChild(code);
document.body.appendChild(pre);
// Re-run highlighting
hljs.highlightAll();
}
// Configure which elements to highlight
hljs.configure({
cssSelector: 'pre code, .code-block code',
classPrefix: 'hljs-'
});
hljs.highlightAll();Highlights a specific DOM code element.
/**
* Highlights a specific DOM element
* @param element - HTML element containing code to highlight
* Element should be a <code> element or contain code text
*/
function highlightElement(element: HTMLElement): void;Usage Examples:
// Highlight specific element
const codeElement = document.querySelector('#my-code-block');
hljs.highlightElement(codeElement);
// Highlight newly created elements
function createHighlightedCode(code, language) {
const codeElement = document.createElement('code');
codeElement.textContent = code;
codeElement.className = `language-${language}`;
const preElement = document.createElement('pre');
preElement.appendChild(codeElement);
// Highlight before adding to DOM
hljs.highlightElement(codeElement);
return preElement;
}
// Highlight elements matching a selector
document.querySelectorAll('.dynamic-code').forEach(element => {
hljs.highlightElement(element);
});
// Re-highlight after content changes
const codeBlock = document.querySelector('#editable-code');
codeBlock.addEventListener('input', () => {
// Clear previous highlighting
codeBlock.removeAttribute('data-highlighted');
codeBlock.className = codeBlock.className.replace(/hljs[^\s]*/g, '');
// Re-highlight
hljs.highlightElement(codeBlock);
});Legacy function for highlighting DOM elements. Use
highlightElement/**
* @deprecated Use highlightElement(element) instead
* Legacy function for highlighting DOM elements
* Will be removed in version 12
* @param element - DOM element to highlight
*/
function highlightBlock(element: HTMLElement): void;For automatic highlighting to work properly, code should be structured as follows:
Basic Structure:
<pre><code class="language-javascript">
const message = "Hello World";
console.log(message);
</code></pre>Language Detection:
<!-- Explicit language specification -->
<pre><code class="language-python">
def hello():
print("Hello World")
</code></pre>
<!-- Language detection via CSS class -->
<pre><code class="javascript">
// Will be detected as JavaScript
</code></pre>
<!-- Auto-detection (no language specified) -->
<pre><code>
SELECT * FROM users WHERE active = 1;
</code></pre>Skip Highlighting:
<!-- Skip highlighting with nohighlight class -->
<pre><code class="nohighlight">
This will not be highlighted
</code></pre>
<!-- Also works with no-highlight -->
<pre><code class="no-highlight">
This will also not be highlighted
</code></pre>Highlight.js integrates with the DOM through several lifecycle events:
Element Processing:
// Elements are processed in document order
// Each element is checked against configuration rules
// Language detection runs for each element individually
// Highlighted elements receive additional CSS classes and attributes
// Check if element was already highlighted
const isHighlighted = element.hasAttribute('data-highlighted');
if (isHighlighted) {
console.log('Element already processed');
}
// Elements receive these attributes after highlighting:
// - data-highlighted: "yes"
// - CSS classes: hljs, language-specific classesPerformance Considerations:
// For large pages, consider selective highlighting
const codeElements = document.querySelectorAll('pre code');
if (codeElements.length > 100) {
// Highlight only visible elements initially
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting && !entry.target.hasAttribute('data-highlighted')) {
hljs.highlightElement(entry.target);
}
});
});
codeElements.forEach(el => observer.observe(el));
} else {
hljs.highlightAll();
}DOM highlighting respects global configuration options:
interface HLJSOptions {
/** Regular expression to identify elements to skip */
noHighlightRe: RegExp; // Default: /^(no-?highlight)$/i
/** Regular expression to detect language from CSS classes */
languageDetectRe: RegExp; // Default: /\blang(?:uage)?-([\w-]+)\b/i
/** CSS class prefix for highlighted elements */
classPrefix: string; // Default: 'hljs-'
/** CSS selector for finding code elements */
cssSelector: string; // Default: 'pre code'
/** Array of allowed languages (null = all languages) */
languages?: string[] | null;
/** Whether to ignore unescaped HTML in code blocks */
ignoreUnescapedHTML?: boolean;
/** Whether to throw errors for unescaped HTML */
throwUnescapedHTML?: boolean;
}Configuration Examples:
// Custom selectors and prefixes
hljs.configure({
cssSelector: '.code-block code, pre code, .highlight',
classPrefix: 'syntax-',
noHighlightRe: /^(skip-highlight|no-syntax)$/i
});
// Restrict to specific languages
hljs.configure({
languages: ['javascript', 'python', 'html', 'css']
});
// HTML security settings
hljs.configure({
ignoreUnescapedHTML: false,
throwUnescapedHTML: true // Throw errors for security issues
});These functions are deprecated but still functional for backwards compatibility:
/**
* @deprecated Use highlightAll() instead
* Legacy initialization function
*/
function initHighlighting(): void;
/**
* @deprecated Use highlightAll() instead
* Legacy DOM-ready initialization
*/
function initHighlightingOnLoad(): void;Migration Example:
// Old approach (deprecated)
hljs.initHighlightingOnLoad();
// New approach (recommended)
document.addEventListener('DOMContentLoaded', () => {
hljs.highlightAll();
});