Remove Single Or Multiple Attributes Using jQuery Examples
When working with different elements of a website, there might be times when you have come across different elements containing a single attribute or multiple attributes. These attributes can, in turn, consist of single or multiple properties. So in this article, I am going to share with you very easy way to get rid of either a single attribute or multiple attributes from any element of your choice using jQuery with easy to follow examples.
How To Remove Single Or Multiple Attributes:
Let’s look at how to do this by means of examples. Assume that we have couple of div elements with attributes. We will see how to remove single & multiple attributes from it.Examples:
Example 1: Remove single attribute from an element:
In this example, we have a div with an attribute called “style”. This “style” attribute contains multiple properties such as “background-color” and “color”. We also have a button and when this button is clicked, we will remove the style attribute and the div will appear plain.
<div id="my_div1" style="background-color: gold; color: darkgreen;">This is a div with a single "style" attribute.</div> <input type="submit" name="sbt_remove_single_property" id="sbt_remove_single_property" value="Remove Style Attribute"> <script type="text/javascript" language="javascript"> $(document).ready(function () { $('#sbt_remove_single_property').on("click", function () { $('#my_div1').removeAttr('style'); }); }); </script>
Example 2: Remove multiple attributes from an element:
In this example, we have a div with an attribute called “style” and “class”. This “style” attribute contains multiple properties such as “background-color” and “color”. The “class” attribute contains multiple properties that affects the way this div is displayed even further. Next, we have a button and when this button is clicked, we will remove both the “style” and the “class” attributes and the div will appear plain.
<div id="my_div2" class="highlight" style="background-color: lightblue; color: purple;">This is a div with multiple attributes (style and class).</div> <input type="submit" name="sbt_remove_multiple_properties" id="sbt_remove_multiple_properties" value="Remove Style and Class Attributes"> <script type="text/javascript" language="javascript"> $(document).ready(function () { $('#sbt_remove_multiple_properties').on("click", function () { $('#my_div2').removeAttr('style class'); }); }); </script>
Conclusion:
So from the above example, we can conclude that we can remove a single attribute or multiple attributes from any element. To remove multiple attributes, simply specifying the attributes separated by space will suffice.