[Edge]。→、
element に登録された全ての属性ノードのコレクションを NamedNodeMap で返します。
返却される値は NamedNodeMapであり、Array ではありません。つまり、Array のメソッドは持っておらず、Attr ノードのインデックスはブラウザーによって変わる可能性があります。より正確に言うと、attributes はその属性に関するあらゆる情報を表す文字列のキーと値の組です。
| element | Element。 |
|---|
基本的な例:
// ドキュメント内の最初の <p> 要素を取得する
var para = document.getElementsByTagName("p")[0];
var atts = para.attributes;
ある要素の全ての属性を走査したい時には、インデックスを使うと便利です。
次の例では、"paragraph" を id に持つ要素の全ての属性ノードを走査し、その属性の値を表示します。
<!DOCTYPE html>
<html>
<head>
<title>Attributes example</title>
<script type="text/javascript">
function listAttributes() {
var paragraph = document.getElementById("paragraph");
var result = document.getElementById("result");
// まず、最初の段落(p1)がなんらかの属性を持っているか確かめよう
if (paragraph.hasAttributes()) {
var attrs = paragraph.attributes;
var output = "";
for(var i = attrs.length - 1; i >= 0; i--) {
output += attrs[i].name + "->" + attrs[i].value;
}
result.value = output;
} else {
result.value = "No attributes to show";
}
}
</script>
</head>
<body>
<p id="paragraph" style="color: green;">Sample Paragraph</p>
<form action="">
<p>
<input type="button" value="Show first attribute name and value"
onclick="listAttributes();">
<input id="result" type="text" value="">
</p>
</form>
</body>
</html>
HTML:
<SPAN id=IdSpan class=赤>SPAN要素</SPAN>
JavaScript:
D=IdSpan.attributes; //=[object]:[object NamedNodeMap]
//0=[object]:[object Attr]
//1=[object]:[object Attr]
//length=[number]:2
//getNamedItem=[function]:function getNamedItem() { [native code] }
//…
更に、D[0]=
=[object]:[object Attr] namespaceURI=[object]:null prefix=[object]:null localName=[string]:id name=[string]:id value=[string]:IdSpan ownerElement=[object]:[object HTMLSpanElement] specified=[boolean]:true nodeType=[number]:2 nodeName=[string]:id …
更に、D[1]=
=[object]:[object Attr] namespaceURI=[object]:null prefix=[object]:null localName=[string]:class name=[string]:class value=[string]:赤 ownerElement=[object]:[object HTMLSpanElement] specified=[boolean]:true nodeType=[number]:2 nodeName=[string]:class …