How to add and remove attribute in jQuery


This example will show you how to add and remove the attribute in HTML/JSP pages using jQuery. To perform the above operation jQuery provides attr() and removeAttr() methods to handle the operation.

attr() method sets or returns attributes and values of the selected elements.

Return the value of an attribute.

$(selector).attr(attribute);

Set the attribute and value.

$(selector).attr(attribute,value);

Set attribute and value using a function.

  $(selector).attr(attribute,function(index,currentvalue));

Set multiple attributes and values.

$(selector).attr({attribute:value, attribute:value,...});

removeAttr() method removes one or more attributes from the selected elements.

$(selector).removeAttr(attribute);

Example of attr()

In this example, we have added the style attribute and set the font size and color.

JS Snippet
$(document).ready(function () {
    $("#add").click(function () {
        $("#ws").attr("style", "font-size:40px;color:#337ab7;");
    });
});
add-attribute.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to add and remove attribute in jQuery</title>       
        <script src="js/jquery-3.1.1.min.js"></script>
        <script>
            $(document).ready(function () {
                $("#add").click(function () {
                    $("#ws").attr("style", "font-size:40px;color:#337ab7;");
                });
            });
        </script>
    </head>
    <body>
        <p id="ws">Welcome to WebSparrow.org</p>
        <button type="button" id="add">Add Attribute</button>        
    </body>
</html>

Example of removeAttr()

In this example, we have removed the style attribute.

JS Snippet
$(document).ready(function () {
    $("#remove").click(function () {
        $("#ws").removeAttr("style");
    });
});
remove-attribute.html
<!DOCTYPE html>
<html>
    <head>
        <title>How to add and remove attribute in jQuery</title>       
        <script src="js/jquery-3.1.1.min.js"></script>
        <script>
            $(document).ready(function () {
                $("#remove").click(function () {
                    $("#ws").removeAttr("style");
                });
            });
        </script>
    </head>
    <body>
        <p id="ws" style="font-size:40px;color:#337ab7;">Welcome to WebSparrow.org</p>
        <button type="button" id="remove">Remove Attribute</button>        
    </body>
</html>

Output:

Welcome to WebSparrow.org


Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.