Methods for working with element attributes, properties, classes, and data attributes. These methods provide comprehensive control over element characteristics and metadata.
Methods for getting and setting HTML attributes.
/**
* Get attribute value or set attribute values on elements
* @param name - Attribute name or object of name-value pairs
* @param value - Attribute value, null to remove, or function
* @returns Attribute value (when getting) or Cheerio instance (when setting)
*/
attr(name?: string | Record<string, string | null>): Record<string, string> | undefined;
attr(name: string): string | undefined;
attr(name: string, value: string | null | ((this: Element, i: number, attr: string) => string)): Cheerio<T>;
attr(attributes: Record<string, string | null>): Cheerio<T>;
/**
* Remove attribute from elements
* @param name - Attribute name to remove
* @returns Cheerio instance for chaining
*/
removeAttr(name: string): Cheerio<T>;Usage Examples:
// Get attributes
$('img').attr('src') // Get src of first img
$('div').attr() // Get all attributes as object
// Set single attribute
$('img').attr('alt', 'Description') // Set alt attribute
$('input').attr('required', null) // Remove required attribute
// Set multiple attributes
$('img').attr({
src: 'image.jpg',
alt: 'Photo',
width: '100'
});
// Set with function
$('li').attr('data-index', (i, current) => i);
// Remove attributes
$('input').removeAttr('disabled') // Remove disabled attribute
$('*').removeAttr('style') // Remove style from all elementsMethods for working with DOM element properties (different from attributes).
/**
* Get property value or set property values on elements
* @param name - Property name or object of name-value pairs
* @param value - Property value or function
* @returns Property value (when getting) or Cheerio instance (when setting)
*/
prop(name?: string | Record<string, any>): any;
prop(name: string): any;
prop(name: string, value: any | ((this: Element, i: number, prop: any) => any)): Cheerio<T>;
prop(properties: Record<string, any>): Cheerio<T>;Usage Examples:
// Get properties
$('input').prop('checked') // Get checked state (boolean)
$('option').prop('selected') // Get selected state
$('div').prop('tagName') // Get tag name (uppercase)
// Set properties
$('input[type="checkbox"]').prop('checked', true) // Check checkbox
$('option').prop('selected', false) // Deselect option
$('input').prop('disabled', true) // Disable input
// Set multiple properties
$('input').prop({
checked: true,
disabled: false,
required: true
});
// Set with function
$('input').prop('value', (i, current) => `Item ${i}`);Methods for working with HTML5 data attributes and custom data storage.
/**
* Get data attribute value or set data values on elements
* @param name - Data attribute name or object of name-value pairs
* @param value - Data value
* @returns Data value (when getting) or Cheerio instance (when setting)
*/
data(name?: string | Record<string, unknown>): unknown | Record<string, unknown>;
data(name: string): unknown;
data(name: string, value: unknown): Cheerio<T>;
data(dataObject: Record<string, unknown>): Cheerio<T>;Usage Examples:
// Get data attributes
$('div').data('user-id') // Get data-user-id attribute
$('div').data() // Get all data attributes as object
// Set data attributes
$('div').data('user-id', 123) // Set data-user-id="123"
$('span').data('config', { active: true }) // Set complex data (JSON)
// Set multiple data attributes
$('.item').data({
'item-id': 456,
'category': 'electronics',
'price': 29.99
});
// Data attribute conversion
$('div').data('count', '5') // Stored as string
$('div').data('count') // Returns "5" or 5 (auto-converted)Methods for working with form element values.
/**
* Get value of form elements or set values
* @param value - Value to set (string or array for multi-select)
* @returns Current value (when getting) or Cheerio instance (when setting)
*/
val(): string | undefined | string[];
val(value: string | string[]): Cheerio<T>;Usage Examples:
// Get form values
$('input[name="username"]').val() // Get input value
$('textarea').val() // Get textarea content
$('select').val() // Get selected option value
$('select[multiple]').val() // Get array of selected values
// Set form values
$('input[name="email"]').val('user@example.com') // Set input value
$('textarea').val('Long text content') // Set textarea content
$('select').val('option2') // Select specific option
$('select[multiple]').val(['opt1', 'opt3']) // Select multiple options
// Clear form values
$('input, textarea').val('') // Clear text inputs
$('select').val(null) // Clear selectionMethods for adding, removing, and checking CSS classes.
/**
* Check if any element has the given class
* @param className - Class name to check
* @returns True if any element has the class
*/
hasClass(className: string): boolean;
/**
* Add class(es) to elements
* @param value - Class name(s) or function returning class names
* @returns Cheerio instance for chaining
*/
addClass(value?: string | ((this: Element, i: number, className: string) => string)): Cheerio<T>;
/**
* Remove class(es) from elements
* @param name - Class name(s) or function, or omit to remove all classes
* @returns Cheerio instance for chaining
*/
removeClass(name?: string | ((this: Element, i: number, className: string) => string)): Cheerio<T>;
/**
* Toggle class(es) on elements
* @param value - Class name(s) or function
* @param stateVal - Force add (true) or remove (false)
* @returns Cheerio instance for chaining
*/
toggleClass(
value?: string | ((this: Element, i: number, className: string) => string),
stateVal?: boolean
): Cheerio<T>;Usage Examples:
// Check for classes
$('.item').hasClass('active') // True if any .item has .active
$('div').hasClass('hidden') // Check for hidden class
// Add classes
$('div').addClass('highlight') // Add single class
$('li').addClass('item selected') // Add multiple classes
$('p').addClass((i, current) => `paragraph-${i}`) // Add with function
// Remove classes
$('.selected').removeClass('selected') // Remove specific class
$('div').removeClass('old deprecated') // Remove multiple classes
$('*').removeClass() // Remove all classes
$('li').removeClass((i, current) =>
current.includes('temp') ? 'temp' : '' // Remove conditionally
);
// Toggle classes
$('.menu').toggleClass('open') // Toggle open class
$('tr').toggleClass('even odd') // Toggle between classes
$('.item').toggleClass('active', true) // Force add active class
$('.button').toggleClass((i, current) =>
current.includes('primary') ? 'secondary' : 'primary'
);Methods for working with inline CSS styles.
/**
* Get CSS property value or set CSS properties
* @param prop - Property name, array of names, or object of name-value pairs
* @param val - Property value or function
* @returns Property value/object (when getting) or Cheerio instance (when setting)
*/
css(prop?: string | string[] | Record<string, string>): Record<string, string> | string | undefined;
css(prop: string): string | undefined;
css(prop: string, val: string | ((this: Element, i: number, style: string) => string | undefined)): Cheerio<T>;
css(properties: Record<string, string>): Cheerio<T>;Usage Examples:
// Get CSS properties
$('div').css('color') // Get color property
$('p').css(['margin', 'padding']) // Get multiple properties
$('span').css() // Get all inline styles
// Set single CSS property
$('div').css('color', 'red') // Set color
$('p').css('font-size', '14px') // Set font size
$('span').css('display', 'none') // Hide element
// Set multiple CSS properties
$('.box').css({
width: '200px',
height: '100px',
'background-color': '#f0f0f0',
'border-radius': '5px'
});
// Set with function
$('li').css('margin-left', (i, current) => `${i * 10}px`);
// Remove CSS properties
$('div').css('color', '') // Remove color property
$('*').removeAttr('style') // Remove all inline stylesUnderstanding when to use attr() vs prop():
// Attributes (HTML attributes, strings)
$('input').attr('checked') // Returns "checked" or undefined
$('input').attr('disabled', 'disabled') // Sets disabled="disabled"
// Properties (DOM properties, proper types)
$('input').prop('checked') // Returns true or false
$('input').prop('disabled', true) // Sets disabled property to true
// Form elements - use prop() for states
$('input[type="checkbox"]').prop('checked', true) // Correct
$('input[type="checkbox"]').attr('checked', 'checked') // Works but not ideal
// Custom attributes - use attr()
$('div').attr('data-custom', 'value') // Custom HTML attributes
$('div').attr('aria-label', 'Description') // ARIA attributesCheerio automatically processes data attributes:
// HTML: <div data-user-id="123" data-is-active="true" data-config='{"theme":"dark"}'>
// Automatic type conversion
$('div').data('user-id') // Returns 123 (number)
$('div').data('is-active') // Returns true (boolean)
$('div').data('config') // Returns {theme: "dark"} (object)
// Raw attribute access
$('div').attr('data-user-id') // Returns "123" (string)
$('div').attr('data-is-active') // Returns "true" (string)Complex class manipulation patterns:
// Conditional class addition
$('.item').each((i, el) => {
const $el = $(el);
if ($el.data('featured')) {
$el.addClass('featured-item');
}
if (i % 2 === 0) {
$el.addClass('even');
}
});
// State-based class management
function updateItemState(items, activeId) {
items.removeClass('active selected') // Clear all state classes
.filter(`[data-id="${activeId}"]`) // Find specific item
.addClass('active selected'); // Add state classes
}
// Toggle with conditions
$('.toggle-button').toggleClass('pressed',
$('.menu').hasClass('open') // Toggle based on other state
);Comprehensive form value management:
// Get all form values
function getFormData(form) {
const data = {};
form.find('input, select, textarea').each((i, el) => {
const $el = $(el);
const name = $el.attr('name');
if (name) {
if ($el.attr('type') === 'checkbox') {
data[name] = $el.prop('checked');
} else if ($el.attr('type') === 'radio') {
if ($el.prop('checked')) {
data[name] = $el.val();
}
} else {
data[name] = $el.val();
}
}
});
return data;
}
// Set form values from object
function setFormData(form, data) {
Object.entries(data).forEach(([name, value]) => {
const $field = form.find(`[name="${name}"]`);
if ($field.attr('type') === 'checkbox') {
$field.prop('checked', !!value);
} else if ($field.attr('type') === 'radio') {
$field.filter(`[value="${value}"]`).prop('checked', true);
} else {
$field.val(value);
}
});
}// Attribute value types
type AttributeValue = string | number | boolean | null | undefined;
// Function types for dynamic values
type AttributeFunction = (this: Element, index: number, attr: string) => string;
type PropertyFunction = (this: Element, index: number, prop: any) => any;
type ClassFunction = (this: Element, index: number, className: string) => string;
type StyleFunction = (this: Element, index: number, style: string) => string | undefined;
// Data attribute types
type DataValue = string | number | boolean | object | null | undefined;