如何使用jQuery删除HTML元素的所有属性?

要删除HTML元素的所有属性,removeAttr()方法将不起作用。为此,创建一个数组,并使用 removeAllAttrs()删除特定HTML元素的所有属性。例如,通过删除img元素的属性来删除图像。

您可以尝试运行以下代码,以了解如何从元素中删除所有属性。我们正在删除img元素属性-

示例

<html>
   <head>
      <title>Selector Example</title>
      <script src = "https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function() {
            $(".remove-attr").click(function(){  
              $.fn.removeAllAttrs= function() {
                 return this.each(function() {
                    $.each(this.attributes, function() {
                      this.ownerElement.removeAttributeNode(this);
                    });
                 });
               };
            $('img').removeAllAttrs();
          });
         });
      </script>
   </head>
   <body>
      <button type="button" class="remove-attr">Remove Image</button>
      <img src="/green/images/logo.png” alt=”MyImage”>
   </body>
</html>