
We can easily add Attribute JQuery to our HTML elements and implement Javascript functionalities in our website. The Attribute addition method can be used to add, change or retrieve data attributes of HTML elements in a dynamic manner.
In this blog, we are going to learn how to add attribute JQuery methods in the HTML document.
| $("selector").attr("attribute_name", "attribute_value"); |
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jQuery Add Attribute</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <button id="btn">Click Me</button> <script> $(document).ready(function(){ $("#btn").attr("title", "Click to perform action"); }); </script> </body> </html> |
| Parameter | Type | Description |
| attributeName | String | The name of the attribute to be added or modified (e.g., "href", "src", "title"). |
| attributeValue | String / Function | The value to be assigned to the attribute. It can be a string or a function that returns a value dynamically. |
| attributesObject | Object | An object containing multiple key-value pairs to set multiple attributes at once. |
| $("#myButton").attr("disabled", "disabled"); |
| $("a").attr("href", "https://www.example.com"); |
| $("img").attr({ "src": "image.jpg", "alt": "Example Image", "width": "300" }); |
| let srcValue = $("img").attr("src"); console.log(srcValue); |
| <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>attr demo</title> <style> em { color: blue; font-weight: bold; } div { color: red; } </style> <script src="https://code.jquery.com/jquery-3.7.1.js"></script> </head> <body> <p>This is a PW Skills Blog <em title="huge, gigantic">large</em> based on web development...</p> The title of the emphasis is:<div></div> <script> var title = $( "em" ).attr( "title" ); $( "div" ).text( title ); </script> </body> </html> |
| $("selector").attr(attribute) |
| $("selector").attr(attribute, value) |
| $("selector").attr(attribute, function(index, currentvalue) |
| $("selector").attr({ attribute: value, attribute:value,....}) |