ctrl+k
Enter a search term above to see results...
Enter a search term above to see results...
Attribute methods in Query allow you to get, set, and remove attributes on DOM elements.
Gets or sets attributes on elements.
$('selector').attr(attributeName)$('selector').attr(attributeName, value)$('selector').attr({attribute1: value1, attribute2: value2})| Name | Type | Description |
|---|---|---|
| attributeName | string | The name of the attribute to get |
Query object (for chaining).
// Get an attribute valueconst href = $('a').attr('href');console.log(href);// Set a single attribute$('img').attr('alt', 'Profile picture');// Set multiple attributes$('input').attr({ 'type': 'text', 'placeholder': 'Enter your name'});Removes an attribute from each element in the set of matched elements.
Boolean Attributes This is helpful for boolean attributes where setting a value like
checked="false"will actually result in checked being set.
$('selector').removeAttr(attributeName)| Name | Type | Description |
|---|---|---|
| attributeName | string | The name of the attribute to remove |
Query object (for chaining).
// Remove the 'disabled' attribute from all buttons$('button').removeAttr('disabled');Gets or sets data attributes on elements. Data attributes are HTML attributes that start with data- and are commonly used to store custom data.
$('selector').data()$('selector').data(key)$('selector').data(key, value)| Name | Type | Description |
|---|---|---|
| key | string | The data attribute key (without ‘data-’ prefix) |
| value | string | The value to set |
Query object (for chaining).
// HTML: <div data-user-id="123" data-role="admin"></div>const allData = $('div').data();console.log(allData); // { userId: "123", role: "admin" }// HTML: <div data-user-id="123"></div>const userId = $('div').data('userId');console.log(userId); // "123"// Set a data attribute$('div').data('theme', 'dark');// Results in: <div data-theme="dark"></div>// HTML:// <div data-id="1" data-name="Alice"></div>// <div data-id="2" data-name="Bob"></div>
// Get specific attribute from multiple elementsconst ids = $('div').data('id');console.log(ids); // ["1", "2"]
// Get all data from multiple elementsconst allData = $('div').data();console.log(allData); // [{ id: "1", name: "Alice" }, { id: "2", name: "Bob" }]
// Set data on multiple elements$('div').data('active', 'true');// Both divs now have data-active="true"userId becomes data-user-id)