A very fast HTML parser, generating a simplified DOM, with basic element query support.
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Comprehensive attribute manipulation and property access with support for both raw and decoded attribute values, class management, and element property inspection.
Methods for getting, setting, and checking HTML attributes with proper encoding/decoding.
/**
* Get decoded attribute value
* @param key - Attribute name (case insensitive)
* @returns Decoded attribute value or undefined if not present
*/
getAttribute(key: string): string | undefined;
/**
* Set attribute value
* @param key - Attribute name
* @param value - Attribute value to set
* @returns HTMLElement for method chaining
*/
setAttribute(key: string, value: string): HTMLElement;
/**
* Remove attribute
* @param key - Attribute name to remove
* @returns HTMLElement for method chaining
*/
removeAttribute(key: string): HTMLElement;
/**
* Check if attribute exists
* @param key - Attribute name to check (case insensitive)
* @returns true if attribute exists, false otherwise
*/
hasAttribute(key: string): boolean;
/**
* Replace all attributes with new set
* @param attributes - Object containing new attributes
* @returns HTMLElement for method chaining
*/
setAttributes(attributes: Attributes): HTMLElement;Usage Examples:
import { parse } from "node-html-parser";
const element = parse('<div class="container" data-id="123">Content</div>');
// Get attributes
console.log(element.getAttribute('class')); // "container"
console.log(element.getAttribute('data-id')); // "123"
console.log(element.getAttribute('missing')); // undefined
// Check attributes
console.log(element.hasAttribute('class')); // true
console.log(element.hasAttribute('id')); // false
// Set attributes
element.setAttribute('id', 'main-div');
element.setAttribute('role', 'main');
console.log(element.getAttribute('id')); // "main-div"
// Remove attributes
element.removeAttribute('data-id');
console.log(element.hasAttribute('data-id')); // false
// Replace all attributes
element.setAttributes({
'class': 'new-class',
'title': 'New title',
'tabindex': '0'
});
console.log(element.toString());
// <div class="new-class" title="New title" tabindex="0">Content</div>Properties for accessing raw and processed attribute collections.
/** Get all attributes as decoded key-value pairs */
get attributes(): Record<string, string>;
/** Get all raw attributes with original encoding */
get rawAttributes(): RawAttributes;
/** Get parsed and decoded attributes (alias for attributes) */
get attrs(): Attributes;
/** Get raw attribute string as it appears in HTML */
rawAttrs: string;Usage Examples:
const element = parse('<div class="test" data-value="hello & world" title="tooltip">Content</div>');
// Get all attributes (decoded)
console.log(element.attributes);
// { class: "test", "data-value": "hello & world", title: "tooltip" }
// Get raw attributes (with original encoding)
console.log(element.rawAttributes);
// { class: "test", "data-value": "hello & world", title: "tooltip" }
// Get raw attribute string
console.log(element.rawAttrs);
// 'class="test" data-value="hello & world" title="tooltip"'
// Iterate over attributes
Object.entries(element.attributes).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});DOMTokenList class providing standard DOM APIs for managing CSS classes.
/** Class list management object */
get classList(): DOMTokenList;
/** Get class names as space-separated string */
get classNames(): string;
interface DOMTokenList {
/** Number of classes */
get length(): number;
/** Array of class names */
get value(): string[];
/** Add class (throws error if class contains whitespace) */
add(className: string): void;
/** Remove class */
remove(className: string): void;
/** Replace one class with another */
replace(oldClass: string, newClass: string): void;
/** Toggle class presence */
toggle(className: string): void;
/** Check if class exists */
contains(className: string): boolean;
/** Get iterator for class names */
values(): IterableIterator<string>;
/** Convert to space-separated string */
toString(): string;
}Usage Examples:
const element = parse('<div class="container active">Content</div>');
// Access classList
const classes = element.classList;
console.log(classes.length); // 2
console.log(classes.value); // ["container", "active"]
console.log(classes.toString()); // "container active"
// Check classes
console.log(classes.contains('active')); // true
console.log(classes.contains('hidden')); // false
// Modify classes
classes.add('new-class');
classes.remove('active');
classes.toggle('highlighted');
console.log(element.className); // "container new-class highlighted"
// Replace class
classes.replace('container', 'wrapper');
console.log(classes.toString()); // "wrapper new-class highlighted"
// Iterate over classes
for (const className of classes.values()) {
console.log(`Class: ${className}`);
}
// Error handling
try {
classes.add('invalid class'); // Throws error - contains space
} catch (error) {
console.error(error.message);
}Direct access to key element properties and identifiers.
/** Element ID attribute value */
id: string;
/** Element tag name in uppercase */
get tagName(): string;
set tagName(name: string): void;
/** Element tag name in lowercase */
get localName(): string;
/** Raw tag name preserving original case */
rawTagName: string;Usage Examples:
const element = parse('<DIV id="main-content" class="wrapper">Content</DIV>');
// Access properties
console.log(element.id); // "main-content"
console.log(element.tagName); // "DIV"
console.log(element.localName); // "div"
console.log(element.rawTagName); // "DIV"
// Modify properties
element.id = "new-id";
element.tagName = "section";
console.log(element.toString());
// <section id="new-id" class="wrapper">Content</section>
// ID changes update attribute
console.log(element.getAttribute('id')); // "new-id"Handle HTML5 data attributes with proper naming conventions:
const element = parse('<div data-user-id="123" data-active="true">User</div>');
// Access data attributes
const userId = element.getAttribute('data-user-id');
const isActive = element.getAttribute('data-active') === 'true';
// Set data attributes
element.setAttribute('data-role', 'admin');
element.setAttribute('data-created', new Date().toISOString());
// Remove data attributes
element.removeAttribute('data-active');Work with attributes containing special characters and HTML entities:
const element = parse('<div title="hello "world"" data-json="{"key":"value"}">Content</div>');
// Get decoded values
console.log(element.getAttribute('title')); // 'hello "world"'
console.log(element.getAttribute('data-json')); // '{"key":"value"}'
// Set values with special characters (automatically encoded)
element.setAttribute('description', 'Text with "quotes" & symbols');
element.setAttribute('data-config', JSON.stringify({ active: true }));Efficiently manage multiple attributes:
const element = parse('<div>Content</div>');
// Set multiple attributes at once
element.setAttributes({
'id': 'bulk-example',
'class': 'demo-element',
'data-version': '2.0',
'role': 'button',
'tabindex': '0',
'aria-label': 'Demo button'
});
// Copy attributes from another element
const source = parse('<span id="source" class="copy-me" title="tooltip">Source</span>');
const target = parse('<div>Target</div>');
// Copy all attributes except tag-specific ones
const attributesToCopy = { ...source.attributes };
delete attributesToCopy.id; // Don't copy ID to avoid duplicates
target.setAttributes(attributesToCopy);
// Conditional attribute setting
const config = {
shouldHaveId: true,
isActive: false,
role: 'button'
};
if (config.shouldHaveId) {
element.setAttribute('id', 'conditional-id');
}
if (config.isActive) {
element.classList.add('active');
}
element.setAttribute('role', config.role);Validate and sanitize attribute values before setting:
function setValidatedAttribute(element: HTMLElement, key: string, value: string) {
// Basic validation
if (!key || key.includes(' ')) {
throw new Error('Invalid attribute name');
}
// Sanitize value
const sanitizedValue = value.trim();
if (sanitizedValue) {
element.setAttribute(key, sanitizedValue);
} else {
element.removeAttribute(key);
}
}
// Safe attribute operations
const element = parse('<div>Content</div>');
try {
setValidatedAttribute(element, 'title', ' Valid title ');
setValidatedAttribute(element, 'data-empty', ' '); // Removes empty attribute
console.log(element.toString());
} catch (error) {
console.error('Validation failed:', error.message);
}interface Attributes {
[key: string]: string;
}
interface RawAttributes {
[key: string]: string;
}
interface KeyAttributes {
id?: string;
class?: string;
}