How to Set and Get the Attribute? jQuery

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).

Get and Set Attribute Value

Key lines:

  • Set value –  $(“#dateTimeStorage”).attr(“currentdatetime”, currentFormattedDateTime); 
  • Get Value –  var currentFormattedDateTime = $(“#dateTimeStorage”).attr(“currentdatetime”); 

How it looks in the browser:

Get and Set attribute value html and jquery

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.

  1.  $(‘#myElement’).removeAttr(‘attributeName’); 
  2.  $(‘#myElement’).attr(‘attributeName’, null); 

More topics in this section:

Leave a Reply

Your email address will not be published. Required fields are marked *