Last Updated on April 18, 2023 by Roshan Parihar
In this tutorial, learn how jQuery add attribute to an HTML elements. The short answer is: use the jQuery attr()
method. You can use this method to add attributes to the HTML element with its relevant attribute value.
If you want to learn more about the jQuery attr method, you have to visit jQuery attr() method page to learn the syntax and more details.
How jQuery Add Attribute to an HTML element
To add attribute to an HTML element using jQuery, you have to use the jQuery attr()
method with the attribute name and a relevant value for the attribute.
Let’s find out how to add a class attribute with the example given below. See the below given example to learn the method and add attribute:-
Add Class Attribute
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<style> .myclass{ background:#ccc; color:red; padding:5px } </style> <script> $(document).ready(function(){ $("#btn-addattr").click(function(){ $("#para-addattr").attr("class","myclass"); }); }); </script> <button id="btn-addattr">Add Attribute</button> <p id="para-addattr">This is the answer to add attributes to an HTML element using jQuery <code>attr()</code> method.</p> |
Output
This is the answer to add attributes to an HTML element using jQuery attr()
method.
The above example adds a class attribute to the HTML <p> tag. The method adds the class attribute to the HTML element as well the styling of the specified class.
You can click the ‘Add Attribute’ button given above to see the class added to the paragraph element.
You May Also Like to Read