Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.
// <a id="home" href="/index.html">Home</a>
const href = $('a#home').attr('href');
"/index.html"
$('img').attr('alt', 'A beautiful landscape');
<img alt="A beautiful landscape">
$('input').attr({
'type': 'text',
'placeholder': 'Enter name',
'readonly': null // Removes attribute
});
<input type="text" placeholder="Enter name">
$('li').attr('data-index', (index) => `item-${index}`);
<li data-index="item-0"></li>
<li data-index="item-1"></li>
| Parameter | Type | Description |
|---|---|---|
| name | string | object | The name of the attribute to set/get, or an object of attribute-value pairs. |
| value | string | number | null | function | The value to set the attribute to. If null, the attribute is removed. If a function, it is called for each element with arguments (index, currentValue). |
Returns: The attribute value (string/undefined) for getter, or the original SR object for setter.