HTMLタグに含まれる全属性を削除するサンプルです。
サンプル
例)タグ(id="p1")に含まれる全属性を削除する
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | <!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>タグの全属性を削除するサンプル</title> <script> function test(){   //id="p1"タグのオブジェクトを取得し変数名objとする   var obj = document.getElementById("p1");   //確認のためobjに含まれる属性数を出力する   console.log("削除前:" + obj.attributes.length);   //objの属性一覧を取得する   var arrAttrib = obj.attributes;   //空の配列を定義(属性名の)   var arr = new Array();   //属性名の配列を生成する   for (var objAttrib of arrAttrib) {     arr.push(objAttrib.name);   }   //objから属性を削除する   for (var attribName of arr) {     obj.removeAttribute(attribName);   }   //確認のためobjに含まれる属性数を出力する   console.log("削除後:" + obj.attributes.length); } </script> </head> <body>   <p id="p1" align="center" class="cls">hoge</p>   <input type="button" value="ボタン" onclick="test();"> </body> </html> | 
- (結果)
- 削除前:3 削除後:0
結果はコンソールに出力されます。
解説
- pタグ(id="p1")に指定されている属性「id」「align」「class」が全て削除されます。