How to add attribute to an HTML element in jQuery
In this tutorial, we are going to see how to add attribute to an HTML element in jQuery. You can use the attr() method of jQuery to add attributes to an HTML element.
In the following example, when you click on the “Select checkbox” button, it dynamically adds the “checked” attribute to the checkbox.
How to add attribute to an HTML element in jQuery
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>How to add attribute to an HTML element</title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(".ajouter-attr").click(function(){ $('input[type="checkbox"]').attr("checked", "checked"); }); }); </script> </head> <body> <button type="button" class="ajouter-attr">Check the checkbox</button> <input type="checkbox"> </body> </html>
Result |
---|