The HTML allows you to add any custom attributes to the page markup. And you can use this data in jQuery(JavaScript).
attr() and removeAttr() Methods
There are two methods in jQuery to perform actions on attributes:
- attr() – used when you need to find out the value of the required attribute, add a new attribute to the element, or change the current value of some attribute to a new one;
- removeAttr() is used to remove a specific attribute from an element or set of elements.
Getting the value of an attribute
Getting the value of a particular attribute in jQuery is done via attr():
.attr(‘attributeName’) , where attributeName – the attribute whose value is to be retrieved.
Set the value of an attribute
Changing the value of an attribute is also done using attr(). To set the value of a single attribute, use .attr(‘attributeName’, value) , where attributeName is the name of the attribute and value is the new value (string, number, or null). If the attribute is set to null, then it will be removed. In jQuery, setting a new attribute or changing an existing one is the same operation.
Example – Get and Set Attribute for Hidden Input
This example demonstrates how to set and read an attribute. By clicking on the ‘Set’ button we get the current date and time and set it to the ‘currentdatetime’ attribute(lines 8,10). And by clicking the ‘Get’ button we read the value from the ‘currentdatetime’ attribute and display it on the ‘dateTimeOutput’ span(lines 14,15).
Key lines:
- Set value – $(“#dateTimeStorage”).attr(“currentdatetime”, currentFormattedDateTime);
- Get Value – var currentFormattedDateTime = $(“#dateTimeStorage”).attr(“currentdatetime”);
Watch my Video with Example
How to remove an attribute from an element in jQuery?
In jQuery, removing an attribute is done using the removeAttr() method. Also, you can remove attributes by setting null value.
- $(‘#myElement’).removeAttr(‘attributeName’);
- $(‘#myElement’).attr(‘attributeName’, null);
More topics in this section: