On This Page
HTML Attributes
Data Attributes
Query - Attributes
Get, set, and remove HTML attributes and data attributes on elements.
HTML Attributes
attr
$('selector').attr(name);$('selector').attr(name, value);$('selector').attr({ name: value, ... });Gets or sets attributes on elements.
Parameters
| Name | Type | Description |
|---|---|---|
| name | string | The attribute name |
| value | string | The value to set |
Returns
- Getting: The attribute value, or array of values for multiple elements
- Setting: Query object (for chaining)
Example
removeAttr
$('selector').removeAttr(name);Removes an attribute from matched elements.
Boolean Attributes Use this for boolean attributes where
checked="false"would still be truthy.
Parameters
| Name | Type | Description |
|---|---|---|
| name | string | The attribute name to remove |
Returns
Query object (for chaining).
Example
addAttr
$('selector').addAttr(name);$('selector').addAttr([name1, name2, ...]);Adds boolean attributes with empty string values. Equivalent to attr(name, '').
Parameters
| Name | Type | Description |
|---|---|---|
| name | string | string[] | Attribute name or array of names |
Returns
Query object (for chaining).
Example
Data Attributes
data
$('selector').data();$('selector').data(key);$('selector').data(key, value);Gets or sets data-* attributes. Keys use camelCase and are converted to kebab-case in the DOM.
Parameters
| Name | Type | Description |
|---|---|---|
| key | string | The data key (without data- prefix) |
| value | string | The value to set |
Returns
- Getting all: Object with all data attributes (or array for multiple elements)
- Getting key: The value (or array for multiple elements)
- Setting: Query object (for chaining)
Example
removeData
$('selector').removeData(keys);Removes data attributes from elements.
Parameters
| Name | Type | Description |
|---|---|---|
| keys | string | string[] | Space-separated string or array of keys to remove |
Returns
Query object (for chaining).