Step 1: Include Jquery on your web page
Before you can use Jquery to set custom attribute values, you need to include jQuery on your web page. You can do this by adding the following code to the section of your HTML document:
1 |
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> |
Step 2: Select the element you want to add a custom attribute value to
To select the HTML element you want to add a custom attribute value to, you can use Jquery’s selector syntax. You can select elements by tag name, class, or ID. For example, to select an element with the class “my-class”, you can use the following code:
1 |
var elem = $('.my-class'); |
Step 3: Set the custom attribute value
Once you have selected the element you want to add a custom attribute value to, you can use Jquery’s .attr() method to set the custom attribute value. The .attr() method takes two arguments: the name of the attribute you want to set, and the value you want to set it to. For example, to set a custom attribute called “data-custom-value” to a value of “my-value”, you can use the following code:
1 |
elem.attr('data-custom-value', 'my-value'); |
Step 4: Verify the custom attribute value has been set
To verify that the custom attribute value has been set on your HTML element, you can use your browser’s developer tools to inspect the element. Look for the custom attribute you set in the element’s attribute list.
Congratulations! You have successfully set a custom attribute value on an HTML element using Jquery.
If you want to learn more about Jquery and its capabilities, check out the official Jquery documentation at jquery.com.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<html> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <div class="my-class">Hello, world!</div> <script> var elem = $('.my-class'); elem.attr('data-custom-value', 'my-value'); </script> </body> </html> |
Output:
<html> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <div class="my-class" data-custom-value="my-value">Hello, world!</div> <script> var elem = $('.my-class'); elem.attr('data-custom-value', 'my-value'); </script> </body> </html>