DOM Manipulation
Relevant source files
The following files were used as context for generating this wiki page:
DOM Manipulation in Cheerio provides a powerful, jQuery-like API for modifying the structure, content, and attributes of parsed HTML and XML documents. It operates on a consistent DOM model derived from domhandler nodes, allowing for efficient server-side document transformation without the overhead of a full browser environment.
The system encompasses structural changes (adding, removing, or wrapping elements), content updates (text and HTML modification), and attribute/property management. It supports various input types for manipulation, including HTML strings, DOM nodes, Cheerio objects, and callback functions that provide dynamic values based on the element's index or current content.
Sources: Readme.md:20-25, src/api/manipulation.spec.ts:1-20
Structural Modification
Cheerio allows for complex restructuring of the DOM tree through insertion and wrapping methods. These operations manage parent-child relationships and sibling order, ensuring that nodes are correctly detached from their previous locations when moved to new ones.
Insertion Logic
Insertion methods such as .append(), .prepend(), .after(), and .before() facilitate the placement of new or existing content relative to selected elements. When existing nodes are inserted, they are moved (detached from the old parent and attached to the new) rather than copied, unless multiple targets are specified, in which case clones are created for all but the last occurrence.
Sources: src/api/manipulation.spec.ts:446-465, src/api/manipulation.spec.ts:588-605
The following diagram illustrates the flow of a node movement operation:
Wrapping and Unwrapping
Wrapping methods provide the ability to enclose elements or their contents within new structures.
.wrap(): Encloses each matched element individually..wrapAll(): Encloses all matched elements together in a single wrapper..wrapInner(): Encloses the child contents of each matched element..unwrap(): Removes the parents of matched elements from the DOM.
Sources: src/api/manipulation.spec.ts:20-40, src/api/manipulation.spec.ts:204-220, src/api/manipulation.spec.ts:365-380
Content and Attribute Manipulation
Cheerio provides specific methods to modify the internal data of nodes, including text, raw HTML, and element attributes.
Content Management
Methods like .text() and .html() act as both getters and setters. When setting content, they effectively clear the existing children of the target element and replace them with the new value. .text() escapes HTML entities to ensure safety, whereas .html() parses the input string as raw markup.
Sources: src/api/manipulation.spec.ts:1176-1200, src/api/manipulation.spec.ts:1280-1300, src/static.spec.ts:90-110
| Method | Role | Behavior |
|---|---|---|
.html() | Getter/Setter | Sets or gets inner HTML. Setting clears children. |
.text() | Getter/Setter | Sets or gets combined text content. Setting escapes entities. |
.empty() | Action | Removes all child nodes from the selection. |
.val() | Getter/Setter | Manages the value of form elements (input, select, etc.). |
| Sources: src/api/manipulation.spec.ts:1176-1185, src/api/manipulation.spec.ts:1280-1290, src/api/attributes.spec.ts:503-520 |
Attribute and Class Control
Attribute manipulation allows for fine-grained control over element metadata. Boolean attributes are handled specifically in HTML mode but treated as standard attributes in XML mode.
Sources: src/api/attributes.spec.ts:25-45, src/api/attributes.spec.ts:155-165
Parsing and Serialization Logic
The manipulation API relies on underlying parsing and serialization mechanisms to convert between strings and node objects.
Static Methods
Static methods on the cheerio object (or the instance returned by load) allow for manipulation outside of a specific selection context.
$.parseHTML(data): Parses a string into an array of DOM nodes. It provides an option to keep or ignore<script>tags for security.$.contains(container, contained): A utility to check if a node is a descendant of another.
Sources: src/static.spec.ts:135-155, src/static.spec.ts:285-300
Parsing Constraints
The parser handles various HTML edge cases, such as implicit tag creation (e.g., adding <tbody> to <table> or <tr> around <td>) and malformed tags. These rules ensure that manipulation results in a valid DOM tree as expected by browser standards.
Sources: src/parse.spec.ts:225-245, src/parse.spec.ts:260-275
Rendering Options
Serialization via .html() or .xml() respects the initial configuration provided during cheerio.load().
- XML Mode: Maintains case sensitivity for tags and attributes (e.g.,
<media:thumbnail />). - Entity Decoding: Can be configured to decode or preserve HTML entities during output.
Sources: src/tests/xml.spec.ts:15-35, src/cheerio.spec.ts:275-290
Summary of Manipulation Operations
DOM Manipulation in Cheerio is designed for speed and flexibility, stripping away browser-specific complexities while maintaining a jQuery-compatible interface. It effectively bridges the gap between raw string parsing and structural DOM tree management, providing robust tools for tasks ranging from web scraping to server-side template modification.
Sources: Readme.md:20-40, src/api/manipulation.spec.ts:1-20