CSS & Styling
Relevant source files
The following files were used as context for generating this wiki page:
CSS & Styling in Cheerio provides a jQuery-compatible API for querying and manipulating the visual presentation of elements within a parsed DOM tree. While Cheerio operates in a server-side environment and does not perform actual layout or rendering, it allows developers to get and set style attributes, manage CSS classes, and resolve computed-like properties such as outerHTML or innerText.
The styling module primarily interacts with the attribs property of a DOM element, specifically targeting the style and class attributes. It provides high-level methods to parse inline CSS strings into objects and vice versa, as well as utility functions for conditional class toggling.
Sources: Readme.md:27-32, src/api/css.spec.ts:8-12
Core API Methods
Cheerio implements several core methods for managing styles and classes. These methods are designed to be chainable and handle multiple elements within a selection simultaneously.
The .css() Method
The .css() method is the primary interface for interacting with the style attribute of elements. It supports retrieving specific properties, setting new values, or passing an object to update multiple styles at once.
| Usage | Description | Result |
|---|---|---|
.css(propertyName) | Gets the value of a style property for the first element. | String or undefined |
.css([prop1, prop2]) | Gets multiple style properties as a key-value object. | Object |
.css(prop, value) | Sets a specific style property for all elements in the set. | Cheerio Instance |
.css(object) | Sets multiple style properties using a map. | Cheerio Instance |
.css(prop, fn) | Sets a property based on a function return value. | Cheerio Instance |
Sources: src/api/css.spec.ts:8-35, src/api/css.spec.ts:98-103
The following sequence diagram illustrates the internal flow when setting a CSS property:
CSS Class Management
Class manipulation is handled through four specialized methods that interact with the class attribute of elements. These methods treat the class attribute as a space-separated list of tokens.
.addClass(className): Adds one or more space-separated classes to every matched element. It avoids duplicates and ignores non-element nodes..removeClass([className]): Removes one, multiple, or all classes from the matched elements..hasClass(className): Determines whether any of the matched elements are assigned the given class..toggleClass(className, [state]): Adds or removes classes based on their presence or a specified boolean state.
Sources: src/api/attributes.spec.ts:466-470, src/api/attributes.spec.ts:515-520, src/api/attributes.spec.ts:566-570, src/api/attributes.spec.ts:689-695
Architectural Logic and Parsing
Cheerio's CSS module includes a specialized parser for the style attribute. This parser is designed to be forgiving and handles malformed CSS declarations commonly found in web scraping scenarios.
Parser Behavior
The parser identifies key-value pairs separated by colons and terminated by semicolons. It is resilient to:
- Whitespace: It allows any whitespace (tabs, newlines, form feeds) between declarations.
- Malformed Entities: It handles cases where values contain colons, such as embedded URLs or base64 data strings.
- Empty Declarations: Blank properties (e.g.,
:#ccc;) or blank values (e.g.,color:;) are ignored during retrieval.
Node Filtering
Style and class methods are designed to operate only on element nodes. If a selection contains text nodes or comment nodes, these methods typically skip them to prevent attribute injection on inappropriate node types.
// Example from tests: (prop, val) should skip text nodes
const $text = load('<a style="test: value;">1</a>TEXT<b style="test: value;">2</b>');
const $body = $text($text('body')[0].children);
$body.css('test', 'value');
// Result only affects <a> and <b>, not the "TEXT" node.
Sources: src/api/css.spec.ts:27-36, src/api/attributes.spec.ts:103-107
Summary of styling-related properties
Beyond the direct CSS methods, several properties and methods influence the "computed" style or output of the document.
| Property | Context | Description |
|---|---|---|
outerHTML | .prop('outerHTML') | Renders the element including its own tags and styles. |
innerText | .prop('innerText') | Returns text content while omitting <style> and <script> blocks. |
textContent | .prop('textContent') | Returns all text content, including raw CSS inside <style> tags. |
xml | load(str, { xml: true }) | Influences attribute casing (e.g., preserving camelCase in styles/attributes). |
Sources: src/api/attributes.spec.ts:316-320, src/api/attributes.spec.ts:348-355, src/tests/xml.spec.ts:36-40
Implementation Details
The styling logic is integrated into the Cheerio prototype. When a method like .css() is called, it iterates over the internal array of Element objects, modifying their attribs dictionary.
// Internal data structure representation
interface Element {
tagName: string;
attribs: {
style?: string;
class?: string;
[attr: string]: string | undefined;
};
// ... other DOM properties
}
Sources: Readme.md:129-140, src/parse.spec.ts:79-84
Summary
CSS & Styling in Cheerio provides a robust, jQuery-like layer over raw HTML attributes. It facilitates data extraction and document modification by treating the style and class attributes as structured data rather than simple strings. This module is essential for tasks ranging from identifying hidden elements (via display: none) to modifying the visual structure of a document before re-serialization.