JQuery has a built-in method that used to delete attribute of elements. This method named removeAttr(). Not only for a single attribute, but JQuery remove attr method also delete many of attributes from the selected element.
The use of removeattr() method is quite easy. You only need to add the attribute’s name that you want to delete in the removeAttr() parameter.
Table of Contents
removeAttr() Syntax
1 | $(selector).removeAttr(attribute) |
Explanation:
selector: the selected HTML elements (can be filled with the class attribute, id attribute,…)
Attribute: The attribute’s name to be deleted. To delete the multiple attributes from the selected elements, please separate them with space.
Delete attribute in JQuery with removeAttr() Method
1. Delete a single attribute
1 2 3 4 5 6 7 8 9 10 | <a style="color:red" href="#" title="this title will remove soon">Click to remove title attribute</a> <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script> <script type="text/javascript"> $(document).ready(function(){ $("a").click(function(){ let a = $(this).removeAttr("title"); console.log(a); }) }) </script> |
2. Removes many attributes
1 2 3 4 5 6 7 8 9 10 | <a style="color:red" href="#" title="this title will remove soon">Click to remove title attribute</a> <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script> <script type="text/javascript"> $(document).ready(function(){ $("a").click(function(){ let a = $(this).removeAttr("title href style"); console.log(a); }) }) </script> |
3. JQuery Remove Disabled Attribute
To enabled/disabled attribute using JQuery, you can use the prop() method. With RemoveAttr, we can also replace the use of the prop() method to activate the element.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <input id="txtinput" value="test input" /> <hr> <button class="btn-prop-disabled">Prop Disabled</button> <button class="btn-prop-enabled">Prop Enabled</button> <button class="btn-remove">Remove Attr</button> <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script> <script type="text/javascript"> $(document).ready(function(){ $(".btn-prop-disabled").click(function(){ $("#txtinput").prop("disabled",true) }) $(".btn-prop-enabled").click(function(){ $("#txtinput").prop("disabled",false) }) $(".btn-remove").click(function(){ $("#txtinput").removeAttr("disabled") }) }) </script> |
Another tutorial : Tutorial Javascript DOM HTML (Include 14 Example) : Easy To Understand
Conclusion
RemoveAttr() is the same as the removeAttribute() method in javascript. The difference is that using JQuery will shorten the time and code’s writing.
Leave a Reply