Home > Article > Web Front-end > How to add and delete attributes in jquery
In jquery, you can use attr() or prop() to add attributes to elements. The syntax is "object.attr("attribute name", "value")" or "object.prop("attribute name", "value")"; you can use removeAttr() to delete attributes, the syntax is "object.removeAttr("attribute name")".
The operating environment of this tutorial: windows7 system, jquery3.2.1 version, Dell G3 computer.
jquery methods to add and delete attributes
1. Use attr() or prop() to add attributes
Both prop() and attr() can be used to set the HTML attributes of elements.
Example 1: Use attr() to add the disabled attribute
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-3.2.1.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { $("textarea").attr("disabled", "disabled"); // $("textarea").attr("disabled","true"); }); }); </script> </head> <body> <textarea></textarea><br><br> <button>让textarea不可编辑</button> </body> </html>
Example 2: Use prop() to add the readonly attribute
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script src="js/jquery-3.2.1.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { $("input").attr("readonly","readonly"); }); }); </script> <style type="text/css"> .intro { font-size: 120%; color: red; } </style> </head> <body> <input type="text" value="hello"/><br /><br /> <button>给input添加只读属性</button> </body> </html>
2. Use removeAttr() to delete attributes.
The removeAttr() method removes attributes from selected elements.
Example: Use removeAttr() to delete the hidden attribute
The hidden attribute specifies that the element is hidden. Hidden elements will not be displayed.
Delete this attribute to allow the element to be displayed.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="js/jquery-3.2.1.min.js"></script> <script> $(function () { $("button").click(function () { $("p").removeAttr("hidden"); }) }) </script> </head> <body> <p>这是一段可见的段落。</p> <p hidden="hidden">这是一段被隐藏的段落,现在显示出来了。</p> <p>这是一段可见的段落。</p> <button>删除hidden属性</button> </body> </html>
Recommended related tutorials: jQuery video tutorial
The above is the detailed content of How to add and delete attributes in jquery. For more information, please follow other related articles on the PHP Chinese website!