How To Add A Value To An Attribute Using jQuery?

How To Add A Value To An Attribute Using jQuery?

To add a value to an attribute using jQuery, you can use the attr function.

Here’s an example of how to use the attr function to add a value to the href attribute of a link element:

$('a').attr('href', 'https://www.nilebits.com'); 

This will set the href attribute of all a elements on the page to https://www.nilebits.com.

You can also use the attr function to set multiple attributes at once by passing it an object that maps attribute names to their corresponding values:

$('a').attr({ 
  'href': 'https://www.nilebits.com', 
  'title': 'Example website' 
}); 

This will set the href and title attributes of all a elements on the page to the specified values.

Keep in mind that the attr function only sets the value of the attribute. If the attribute does not already exist, it will not be added to the element. To add a new attribute to an element, you can use the attr function to set the value of the attribute, or you can use the prop function to set the value and add the attribute if it does not already exist.

Share this post

Leave a Reply

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