How can I add an attribute into specific HTML tags in jQuery?

Use the attr() method to add an attribute into specific HTML tags in jQuery. This method allows you to dynamically add custom attributes to HTML elements after the page has loaded.

Syntax

The basic syntax for adding attributes is ?

$(selector).attr(attributeName, attributeValue);

Example

You can try to run the following code to learn how to add an attribute into specific HTML tags ?

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            // Add custom attribute to button with class 'button1'
            $("button.button1").attr("myid", "myvalue");
            
            // Click handler to check if attribute was added
            $('button').on('click', function() {
                if (this.hasAttribute("myid")) {
                    alert('True: The new attribute added successfully.');
                } else {
                    alert('False: No custom attribute found.');
                }
            });
        });
    </script>
</head>
<body>
    <h3>Click the button to verify the attribute</h3>
    <button class='button1'>
        Button 1
    </button>
</body>
</html>

The output of the above code is ?

When you click "Button 1", an alert will display:
"True: The new attribute added successfully."

Adding Multiple Attributes

You can also add multiple attributes at once using an object ?

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            // Add multiple attributes at once
            $("#myDiv").attr({
                "data-role": "content",
                "data-theme": "blue",
                "title": "Custom Title"
            });
            
            $("#checkBtn").click(function(){
                var role = $("#myDiv").attr("data-role");
                var theme = $("#myDiv").attr("data-theme");
                var title = $("#myDiv").attr("title");
                alert("Role: " + role + ", Theme: " + theme + ", Title: " + title);
            });
        });
    </script>
</head>
<body>
    <div id="myDiv">This div will have multiple attributes added</div>
    <button id="checkBtn">Check Attributes</button>
</body>
</html>

Conclusion

The jQuery attr() method provides a simple way to dynamically add attributes to HTML elements, allowing you to modify element properties and store custom data after page load.

Updated on: 2026-03-13T18:12:43+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements