Skip to content

Repository files navigation

HTML Transformer

NPM VersionGitHub Actions Workflow Status

A flexible and powerful HTML transformation library that allows you to apply rules to HTML content using CSS selectors.

Features

  • Transform HTML content from various input types (string, Buffer, Readable stream, or Cheerio API)
  • Apply multiple transformation rules in sequence
  • Use any valid CSS selector supported by Cheerio (including complex pseudo-selectors)
  • Support for asynchronous transformation rules
  • Modify content, attributes, structure, and more
  • Transform elements in both <head> and <body> sections

Installation

npm install @packt/html-transformer

Usage

Basic Example

import{Transformer,TranformationRule}from'@packt/html-transformer';// Define transformation rulesconstrules: TranformationRule[]=[{selector: ['h1'],// Target all h1 elementsrule: async(node,$)=>{node.addClass('title');node.text(`Modified: ${node.text()}`);}},{selector: ['a'],// Target all linksrule: async(node,$)=>{consthref=node.attr('href');if(href&&!href.startsWith('https://')){node.attr('href',`https://example.com${href}`);}}}];// Create transformerconsttransformer=newTransformer(rules);// Transform HTML stringconsthtml='<html><body><h1>Original Title</h1><a href="/link">Link</a></body></html>';constresult=awaittransformer.transform(html);console.log(result);// Outputs: HTML with modified title and link

Using Multiple Input Types

The transformer accepts various input types:

// String inputconsthtmlString='<div>Hello world</div>';constresult1=awaittransformer.transform(htmlString);// Buffer inputconstbuffer=Buffer.from('<div>Hello world</div>');constresult2=awaittransformer.transform(buffer);// Stream inputconststream=Readable.from(['<div>Hello',' world</div>']);constresult3=awaittransformer.transform(stream);// Cheerio API inputconst$=cheerio.load('<div>Hello world</div>');awaittransformer.transform($);constresult4=$.html();

Complex Selectors

The library supports all CSS selectors available in Cheerio:

construles: TranformationRule[]=[{// Target divs that contain spansselector: ['div:has(span)'],rule: async(node,$)=>{node.addClass('has-span');}},{// Target the second item in listsselector: ['li:nth-child(2)'],rule: async(node,$)=>{node.addClass('second-item');}},{// Target paragraphs that don't have a specific classselector: ['p:not(.exclude)'],rule: async(node,$)=>{node.addClass('included');}},{// Target multiple selectors in one ruleselector: ['h1','h2','h3'],rule: async(node,$)=>{node.addClass('heading');}}];

Modifying the Document Head

You can also target and modify elements in the <head> section:

construles: TranformationRule[]=[{selector: ['title'],rule: async(node,$)=>{node.text('New Page Title');}},{selector: ['meta[name="description"]'],rule: async(node,$)=>{node.attr('content','Updated description for SEO');}},{selector: ['head'],rule: async(node,$)=>{// Add a new meta tagnode.append('<meta name="robots" content="noindex">');}}];

Common Transformations

Adding Classes

{selector: ['.target'],rule: async(node,$)=>{node.addClass('new-class');}}

Changing Attributes

{selector: ['img'],rule: async(node,$)=>{node.attr('alt','Descriptive alt text');node.attr('loading','lazy');}}

Wrapping Elements

{selector: ['table'],rule: async(node,$)=>{node.wrap('<div class="table-responsive"></div>');}}

Modifying Content

{selector: ['p'],rule: async(node,$)=>{consttext=node.text();node.html(`<strong>${text}</strong>`);}}

Using the Full Cheerio API

The rule function provides access to the Cheerio API, allowing for more complex manipulations:

{selector: ['article'],rule: async(node,$)=>{// Find all images without alt text within this articleconstimages=node.find('img:not([alt])');images.each((i,img)=>{$(img).attr('alt','Article image');});// Add a class to all paragraphs within this articlenode.find('p').addClass('article-text');}}

API Reference

Class: Transformer

The main class for transforming HTML.

Constructor

constructor(rules: TranformationRule[])

Creates a new Transformer instance with the specified rules.

Methods

asynctransform($: CheerioAPI): Promise<void>;asynctransform(html: string): Promise<string>;asynctransform(html: Buffer): Promise<string>;asynctransform(html: Readable): Promise<string>;

Transforms the input HTML according to the rules.

Interface: TranformationRule

interfaceTranformationRule{selector: string[];// Array of CSS selectorsrule: (node: Cheerio<AnyNode>,$: CheerioAPI)=>Promise<void>;}
  • selector: An array of CSS selectors that determine which elements the rule will be applied to
  • rule: An async function that receives the matched element and the Cheerio API instance

License

MIT

About

A flexible and powerful HTML transformation library that allows you to apply rules to HTML content using CSS selectors.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages