or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

attributes.mdforms.mdindex.mdloading.mdmanipulation.mdstatic-methods.mdtraversal.mdutils.md
tile.json

manipulation.mddocs/

DOM Manipulation

Methods for modifying the DOM structure including adding, removing, and replacing elements. These methods allow you to change the content and structure of the document dynamically.

Capabilities

Content Insertion

Methods for adding content to elements.

/**
 * Insert content as last child of each element
 * @param elems - Content to append (elements, HTML strings, or functions)
 * @returns Original Cheerio instance for chaining
 */
append(...elems: BasicAcceptedElems<AnyNode>[]): Cheerio<T>;

/**
 * Insert content as first child of each element
 * @param elems - Content to prepend (elements, HTML strings, or functions)
 * @returns Original Cheerio instance for chaining
 */
prepend(...elems: BasicAcceptedElems<AnyNode>[]): Cheerio<T>;

/**
 * Insert elements as last child of target
 * @param target - Target element(s) to append to
 * @returns Original Cheerio instance for chaining
 */
appendTo(target: BasicAcceptedElems<AnyNode>): Cheerio<T>;

/**
 * Insert elements as first child of target
 * @param target - Target element(s) to prepend to
 * @returns Original Cheerio instance for chaining
 */
prependTo(target: BasicAcceptedElems<AnyNode>): Cheerio<T>;

Usage Examples:

// Append content
$('ul').append('<li>New item</li>')           // Add as last child
$('div').append($('<span>Text</span>'))       // Append Cheerio object
$('p').append((i, html) => ` (${i})`)        // Append with function

// Prepend content
$('ul').prepend('<li>First item</li>')        // Add as first child
$('div').prepend($('<h3>Title</h3>'))         // Prepend Cheerio object

// Append/prepend to target
$('<li>Item</li>').appendTo('ul')             // Append to ul elements
$('<h1>Title</h1>').prependTo('.container')  // Prepend to .container

Adjacent Insertion

Methods for inserting content adjacent to elements.

/**
 * Insert content after each element
 * @param elems - Content to insert (elements, HTML strings, or functions)
 * @returns Original Cheerio instance for chaining
 */
after(...elems: BasicAcceptedElems<AnyNode>[]): Cheerio<T>;

/**
 * Insert content before each element
 * @param elems - Content to insert (elements, HTML strings, or functions)
 * @returns Original Cheerio instance for chaining
 */
before(...elems: BasicAcceptedElems<AnyNode>[]): Cheerio<T>;

/**
 * Insert elements after target
 * @param target - Target element(s) to insert after
 * @returns Original Cheerio instance for chaining
 */
insertAfter(target: BasicAcceptedElems<AnyNode>): Cheerio<T>;

/**
 * Insert elements before target
 * @param target - Target element(s) to insert before
 * @returns Original Cheerio instance for chaining
 */
insertBefore(target: BasicAcceptedElems<AnyNode>): Cheerio<T>;

Usage Examples:

// Insert after/before
$('h1').after('<hr>')                        // Insert hr after h1
$('p').before('<div>Intro</div>')            // Insert div before p
$('.item').after((i, html) => `<span>${i}</span>`) // Insert with function

// Insert relative to target
$('<hr>').insertAfter('h1')                  // Insert hr after h1 elements
$('<div>Note</div>').insertBefore('.important') // Insert before .important

Wrapping

Methods for wrapping elements with other elements.

/**
 * Wrap each element with DOM structure
 * @param wrapper - Wrapper element or HTML string
 * @returns Original Cheerio instance for chaining
 */
wrap(wrapper: AcceptedElems<AnyNode>): Cheerio<T>;

/**
 * Wrap content of each element
 * @param wrapper - Wrapper element or HTML string
 * @returns Original Cheerio instance for chaining
 */
wrapInner(wrapper: AcceptedElems<AnyNode>): Cheerio<T>;

/**
 * Wrap all elements as single group
 * @param wrapper - Wrapper element or HTML string
 * @returns Original Cheerio instance for chaining
 */
wrapAll(wrapper: AcceptedElems<T>): Cheerio<T>;

/**
 * Remove parent wrapper from elements
 * @param selector - Optional selector to filter which parents to remove
 * @returns Original Cheerio instance for chaining
 */
unwrap(selector?: string): Cheerio<T>;

Usage Examples:

// Wrap each element
$('img').wrap('<div class="image-container"></div>') // Wrap each img
$('p').wrap('<article></article>')           // Wrap each p in article

// Wrap inner content
$('div').wrapInner('<span></span>')          // Wrap content of each div
$('td').wrapInner('<strong></strong>')       // Wrap cell content

// Wrap all elements together
$('.item').wrapAll('<div class="items"></div>') // Wrap all .item in single div

// Remove wrapper
$('span').unwrap()                           // Remove parent of each span
$('.wrapped').unwrap('div')                  // Remove parent div only

Element Removal

Methods for removing elements from the DOM.

/**
 * Remove elements and their children from DOM
 * @param selector - Optional selector to filter which elements to remove
 * @returns Original Cheerio instance for chaining
 */
remove(selector?: string): Cheerio<T>;

/**
 * Remove all children from elements
 * @returns Original Cheerio instance for chaining
 */
empty(): Cheerio<T>;

/**
 * Replace elements with new content
 * @param content - Content to replace with (elements, HTML, or function)
 * @returns Original Cheerio instance for chaining
 */
replaceWith(content: AcceptedElems<AnyNode>): Cheerio<T>;

Usage Examples:

// Remove elements
$('.delete-me').remove()                     // Remove elements from DOM
$('li').remove('.completed')                 // Remove completed li elements
$('script').remove()                         // Remove all script tags

// Empty elements
$('div').empty()                             // Remove all children
$('.container').empty()                      // Clear container content

// Replace elements
$('b').replaceWith('<strong></strong>')      // Replace b with strong
$('.old').replaceWith($('<div class="new">New</div>')) // Replace with new element
$('span').replaceWith((i, html) => `<em>${html}</em>`) // Replace with function

Content Access and Modification

Methods for getting and setting element content.

/**
 * Get HTML content of first element or set HTML content of all elements
 * @param str - HTML string to set (optional)
 * @returns HTML string (when getting) or Cheerio instance (when setting)
 */
html(str?: string | Cheerio<AnyNode>): Cheerio<T> | string | null;

/**
 * Get text content or set text content of elements
 * @param str - Text string or function to set (optional)
 * @returns Text string (when getting) or Cheerio instance (when setting)
 */
text(str?: string | ((this: AnyNode, i: number, text: string) => string)): Cheerio<T> | string;

/**
 * Convert collection to HTML string (alias for .html())
 * @returns HTML string representation
 */
toString(): string;

Usage Examples:

// Get/set HTML content
$('div').html()                              // Get HTML of first div
$('p').html('<strong>Bold text</strong>')    // Set HTML of all p elements
$('.content').html($('<span>Dynamic</span>')) // Set HTML with Cheerio object

// Get/set text content
$('h1').text()                               // Get text of first h1
$('p').text('New text content')              // Set text of all p elements
$('span').text((i, txt) => `${i}: ${txt}`)  // Set text with function

// Convert to string
$('div').toString()                          // HTML representation

Element Cloning

Method for creating copies of elements.

/**
 * Create a deep copy of the element collection
 * @returns New Cheerio instance with cloned elements
 */
clone(): Cheerio<T>;

Usage Examples:

// Clone elements
const originalList = $('ul');
const clonedList = originalList.clone();     // Deep copy of ul and contents

// Clone and modify
$('.template').clone()
  .removeClass('template')
  .addClass('instance')
  .appendTo('#container');

// Clone for reuse
const itemTemplate = $('.item-template').clone();
itemTemplate.find('.name').text('John');
itemTemplate.appendTo('.items');

Advanced Manipulation

Internal utility methods and advanced manipulation techniques.

/**
 * Internal method to create DOM array from various inputs
 * @param elem - Elements to process
 * @param clone - Whether to clone elements
 * @returns Array of DOM nodes
 */
_makeDomArray<T>(
  elem?: BasicAcceptedElems<AnyNode> | BasicAcceptedElems<AnyNode>[],
  clone?: boolean
): AnyNode[];

Advanced Usage Examples:

// Complex content insertion with functions
$('li').append(function(index, html) {
  return `<span class="index">${index}</span>`;
});

// Conditional manipulation
$('div').each(function(i, el) {
  const $el = $(el);
  if ($el.hasClass('special')) {
    $el.wrap('<div class="special-wrapper"></div>');
  } else {
    $el.addClass('regular');
  }
});

// Chaining multiple operations
$('.items')
  .empty()                                   // Clear existing content
  .append('<h3>New Items</h3>')             // Add header
  .append(data.map(item => `<div>${item.name}</div>`)) // Add items
  .find('div')                              // Select added items
  .addClass('item')                         // Add class to items
  .first()                                  // Select first item
  .addClass('first');                       // Mark as first

// Dynamic content creation
function createCard(title, content) {
  return $('<div class="card"></div>')
    .append($('<h4></h4>').text(title))
    .append($('<p></p>').text(content));
}

$('.cards').append(createCard('Title', 'Content'));

Content Types

// Basic accepted element types
type BasicAcceptedElems<T extends AnyNode> = ArrayLike<T> | T | string;

// Accepted elements including functions
type AcceptedElems<T extends AnyNode> = 
  BasicAcceptedElems<T> | 
  ((this: T, i: number, el: T) => BasicAcceptedElems<T>);

// Function signatures for content generation
type ContentFunction<T> = (this: T, index: number, currentContent: string) => string;
type ElementFunction<T> = (this: T, index: number, element: T) => BasicAcceptedElems<AnyNode>;

Error Handling

Manipulation methods are generally robust but can encounter issues:

  • Invalid HTML: Malformed HTML strings may not parse correctly
  • Missing targets: Operations on non-existent elements are ignored
  • Memory limits: Very large DOM manipulations may exceed memory limits
  • Circular references: Avoid creating circular DOM structures

Safe Manipulation Patterns:

// Check existence before manipulation
if ($('.target').length > 0) {
  $('.target').append('<div>Content</div>');
}

// Safe content setting
$('div').html(content || '');                // Fallback for null/undefined

// Error handling for complex operations
try {
  $('.items').empty().append(complexContent);
} catch (error) {
  console.error('Manipulation failed:', error.message);
  $('.items').html('<p>Error loading content</p>');
}