Attributes & Properties
Relevant source files
The following files were used as context for generating this wiki page:
The Attributes & Properties module in Cheerio provides a jQuery-like API for getting, setting, and removing data associated with DOM elements. This includes standard HTML attributes, DOM properties, CSS styles, and data-specific attributes. Cheerio operates on a consistent DOM model where elements contain an attribs object storing their raw attributes as key-value pairs.
This system is designed to be fast and flexible, supporting both HTML and XML modes. In HTML mode, Cheerio handles boolean attributes (like autofocus or checked) and performs type coercion for data attributes, whereas XML mode treats attributes as literal strings.
Sources: Readme.md:52-60, src/api/attributes.spec.ts:161-168, src/parse.spec.ts:89-98
Attribute Management
Attribute management is primarily handled through the .attr() and .removeAttr() methods. Attributes are stored in the attribs property of a domhandler Element.
Core Attribute Methods
- Getter:
.attr(name)retrieves the value of a specific attribute for the first element in the selection. If no name is provided, it returns all attributes as an object. - Setter:
.attr(name, value)sets an attribute for all elements in a selection. It also accepts a map (object) to set multiple attributes at once or a function to calculate values dynamically. - Removal:
.removeAttr(name)removes one or more space-separated attributes from the elements.
The diagram shows the logic flow for the .attr() method, distinguishing between getting and setting behaviors.
Sources: src/api/attributes.spec.ts:17-158, src/parse.spec.ts:89-93
Boolean and XML Attributes
In HTML mode, boolean attributes return their name as the value when present (e.g., autofocus="autofocus"). In XML mode, these are treated as standard attributes without special boolean logic.
Sources: src/api/attributes.spec.ts:38-41, src/api/attributes.spec.ts:161-168
Property Handling
Properties represent the live state or calculated values of DOM nodes. Unlike attributes, which are static strings from the markup, properties can include complex objects (like style objects) or calculated strings (like outerHTML).
| Property | Description |
|---|---|
tagName / nodeName | Returns the element's tag name in uppercase. |
checked | Boolean state for inputs; updates the checked attribute synchronously. |
href / src | Resolved URLs based on the baseURI configuration. |
outerHTML | Renders the selection including its own tags. |
innerHTML | Renders the children of the current node. |
textContent | Returns text including script and style tags. |
innerText | Returns text excluding script and style tags. |
Sources: src/api/attributes.spec.ts:177-319, Readme.md:95-103
URL Resolution Logic
When accessing href or src via .prop(), Cheerio resolves relative paths if a baseURI was provided during the load process.
Sources: src/api/attributes.spec.ts:240-272
Data Attributes
The .data() method manages data-* attributes. It provides a cache layer that is distinct from the raw attribs object after the first access.
Features of the Data API
- CamelCase Conversion: Hyphenated attributes like
data-foo-barare accessed viafooBar. - Type Coercion: Values that look like JSON, booleans, or numbers are automatically parsed when read from the markup.
- Persistence: Setting data via
.data(key, val)does not update the underlyingdata-*attribute in the HTML; it is stored in an internal cache.
Sources: src/api/attributes.spec.ts:335-465
CSS Styling
The .css() method interacts with the style attribute. It parses the style string into a key-value object and vice-versa.
- Parsing: Corrects for malformed CSS and handles embedded URLs (e.g.,
url(data:...)) without mangling them. - Iteration: Supports setting styles via functions, passing the current index and existing value to the callback.
- Unsetting: Passing an empty string
''to a CSS property removes it from thestyleattribute.
Sources: src/api/css.spec.ts:7-105
Class Manipulation
Cheerio provides dedicated methods for the class attribute, treating it as a space-separated list of tokens.
| Method | Logic |
|---|---|
.hasClass(name) | Checks if the class attribute contains the specified token. |
.addClass(name) | Appends a class if not already present. |
.removeClass(name) | Removes specific classes or all classes if no argument is provided. |
.toggleClass(name, toggle) | Adds/removes classes based on their current presence or a boolean switch. |
Sources: src/api/attributes.spec.ts:489-724
Security Considerations
The Attributes & Properties module is subject to security boundaries defined in the project's threat model:
- XSS Enablement: Cheerio's serializer must correctly escape attributes to prevent injection. For example, setting an
hrefto a malicious script should result in encoded output that is safe if rendered literally. - Sanitization: Cheerio is not a sanitizer. Users are responsible for sanitizing attribute values if the output is intended for a browser.
- Prototype Pollution: API calls are designed to prevent modification of
Object.prototypethrough parsed content.
Sources: THREAT_MODEL.md:27-46, src/api/attributes.spec.ts:107-119
Summary
The Attributes & Properties system provides a comprehensive toolkit for DOM manipulation. By distinguishing between attributes (markup state), properties (live/calculated state), and data (application state), Cheerio allows for precise control over document metadata. The implementation ensures that CSS and Class manipulations remain synchronized with the underlying attribs object while maintaining high performance across both HTML and XML environments.