jQuery attr() Method
The jQuery attr() method is a versatile tool for manipulating attributes of HTML elements. It allows you to retrieve, modify, or set attribute values, enabling dynamic changes to elements' behavior and appearance. Here are examples illustrating the usage of the attr() method:
Getting Attribute Value
Consider an HTML anchor (<a>) element:
To retrieve the value of the href attribute using jQuery:
Setting Attribute Value
You can use the attr() method to set or modify attribute values:
This will set the target attribute to "_blank," making the link open in a new tab.
Manipulating Multiple Attributes
The attr() method can also modify multiple attributes at once by passing an object with attribute-value pairs:
In this example, both the href and target attributes of the link will be updated.
Removing an Attribute
To remove an attribute, set its value to null:
This will remove the target attribute from the link.
Working with Custom Attributes
The attr() method can also manage custom attributes:
jQuery Get Attribute
jQuery Set Attribute
The attr() method is a valuable tool for handling attributes, whether standard HTML attributes or custom ones. It's important to note that if you're dealing with properties like checked or disabled, it's often better to use the prop() method instead.