DOM

Element.getAttributeNames() メソッド

 編集:2022.09.21 by T.A.

[Edge]。→

element に指定されている属性の名前を文字列の配列で返します。要素に属性がない場合は、空の配列を返します。

getAttributeNames() を getAttribute() と共に使用すると、Element.attributes にアクセスするよりメモリー効率やパフォーマンスが良くなります。

構文
element.getAttributeNames()
element Element
戻り値

Array。要素に属性がない場合は、空の配列を返します。

要素の属性に対して反復処理する:

for(let name of element.getAttributeNames()) {
  let value = element.getAttribute(name);
  console.log(name, value);
}
代替モジュール
if (Element.prototype.getAttributeNames == undefined) {
  Element.prototype.getAttributeNames = function () {
    var attributes = this.attributes;
    var length = attributes.length;
    var result = new Array(length);
    for (var i = 0; i < length; i++) {
      result[i] = attributes[i].name;
    }
    return result;
  };
}

HTML:

<SPAN id=IdTest class="Test Test2" style="color:red; font-size:30px;">SPAN要素</SPAN>

JavaScript:

D=IdTest.getAttributeNames(); //=[object]:id,class,style
	//0=[string]:id
	//1=[string]:class
	//2=[string]:style

更に、

A=document.createAttribute('Test'); //属性「Test」の生成。
A.value='サンプル';                 //値も設定。
IdTest.setAttributeNode(A);         //テスト要素に属性組み込み。
D=IdTest.getAttributeNames(); //=[object]:id,class,style,test
	//0=[string]:id
	//1=[string]:class
	//2=[string]:style
	//3=[string]:test

テスト