如何刪除 HTML 元素的所有屬性


要刪除 HTML 元素的所有屬性,removeAttr() 方法無效。為此,建立一個數組並使用 removeAllAttrs() 刪除特定 HTML 元素的所有屬性。例如,透過刪除 img 元素的屬性來刪除影像。

可以嘗試執行以下程式碼以瞭解如何從元素刪除所有屬性。我們將刪除 img 元素屬性 −

示例

動態演示

<html>
   <head>
      <title>Selector Example</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/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>

更新於:2020 年 2 月 13 日

1K+ 次瀏覽

開啟你的 職業生涯

完成本課程獲得認證

開啟學習
廣告