Query - Attributes API reference for Query methods related to attribute manipulation tag Guide

Query - Attributes

Attribute methods in Query allow you to get, set, and remove attributes on DOM elements.

attr

Gets or sets attributes on elements.

Syntax

Get

$('selector').attr(attributeName)

Set

$('selector').attr(attributeName, value)
$('selector').attr({attribute1: value1, attribute2: value2})

Parameters

NameTypeDescription
attributeNamestringThe name of the attribute to get

Returns

Get

Query object (for chaining).

Set

  • Single Element The attribute value of that element.
  • Multiple Elements An array of attribute value , one for each matched element.

Usage

Get an Attribute

// Get an attribute value
const href = $('a').attr('href');
console.log(href);

Set an Attribute

// Set a single attribute
$('img').attr('alt', 'Profile picture');

Set Multiple Attributes

// Set multiple attributes
$('input').attr({
'type': 'text',
'placeholder': 'Enter your name'
});

removeAttr

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.

Syntax

$('selector').removeAttr(attributeName)

Parameters

NameTypeDescription
attributeNamestringThe name of the attribute to remove

Returns

Query object (for chaining).

Example

// Remove the 'disabled' attribute from all buttons
$('button').removeAttr('disabled');