← Back to Index

.attr()

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.

Examples

1. Get attribute

// <a id="home" href="/index.html">Home</a>
const href = $('a#home').attr('href');

Result

"/index.html"

2. Set single attribute

$('img').attr('alt', 'A beautiful landscape');

Result

<img alt="A beautiful landscape">

3. Set multiple attributes

$('input').attr({
     'type': 'text',
     'placeholder': 'Enter name',
     'readonly': null // Removes attribute
});

Result

<input type="text" placeholder="Enter name">

4. Set using a function

$('li').attr('data-index', (index) => `item-${index}`);

Result

<li data-index="item-0"></li>
<li data-index="item-1"></li>

Parameters

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.