How to Add an Attribute to an HTML Element with jQuery

In this article, we show how to add an attribute to an HTML element with jQuery.
jQuery has a attr() function, which takes in 2 parameters.
The first attribute is the name of the attribute. The second attribute is the value assigned to this attribute.
This is a powerful function because adding attributes to an element or elements can have powerful effects on the item(s).
Let's give an example of how this works.
Below is a like button that can be toggled on and off. If pressed and turned on, all hyperlinks on the page become yellow.
If toggled, again these hyperlinks go back to their original colors.
We change the color of the hyperlinks by adding an attribute to the a tags on the page.
The jQuery code to do this is shown below.
This jQuery code adds a style attribute to all the anchor tags on the page that makes the color of the links yellow.
The attr() function adds an attribute to an existing HTML element on the page.
Again, it takes in 2 parameters.
The first is the name of the attribute. The second is the value you are setting the attribute to.
The full code for this jQuery function on this page with the like button is shown below.
So we can add any attribute we want to any HTML element.
As another example, let's say we want to make all the anchor tags on our page open on a new page. We can do this by adding the attribute, "target", and setting it to, "_blank".
Now all of the anchor tags on the page will open on a new link.
The same is true for adding custom attributes to an HTML element using jQuery.
Below is code to add a custom attribute to an HTML element with jQuery.
So the code above sets the custom attribute, 'data-elementvalue' to the value of 'z-button'.
And this is how to add an attribute to an HTML element with jQuery.
