[JavaScript General] 属性値を取得/設定する

memo.

[markdown]

JavaScript本格入門 ~モダンスタイルによる基礎からAjax・jQueryまで
山田 祥寛
技術評論社
売り上げランキング: 12,960

## 要素ノードの同名プロパティとしてアクセスする

> * [Element.className – Web APIs | MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/className)

“`javascript
const url = document.getElementById(‘url’);
console.log(url.href);
const p = document.getElementById(‘cap’);
console.log(p.className);
“`

`class` はコンフリクトするので、例外的に `className` となる。

### getAttribute / setAttribute

属性と名前の違いを意識せずに利用できる。
スクリプトから動的に変更可能。

> * [element.getAttribute – Web API インターフェイス | MDN](https://developer.mozilla.org/ja/docs/Web/API/Element/getAttribute)
> * [element.setAttribute – Web API インターフェイス | MDN](https://developer.mozilla.org/ja/docs/Web/API/element/setAttribute)

“`javascript
const p = document.getElementById(‘cap’);
console.log(p.getAttribute(‘class’));
const url = document.getElementById(‘url’);
console.log(url.getAttribute(‘href’));
“`

“`javascript
// getAttribute / setAttribute
const url = document.getElementById(‘url’);
let link = url.getAttribute(‘href’);
console.log(link); // ”
url.setAttribute(‘href’, ‘//www.google.co.jp/’);
link = url.getAttribute(‘href’);
console.log(link); // ‘//www.google.co.jp/’
“`

## 不特定の属性を取得する

> * [Element.attributes – Web APIs | MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/attributes)

See the Pen JavaScript Element.attributes by DriftwoodJP (@DriftwoodJP) on CodePen.

IE の attributes プロパティでは、タグに指定していない属性も含めて出力されてしまう。
ここでは最低限 nodeValue プロパティが空でない属性のみ出力するようにフィルタしている。

> * [JavaScriptのDOM Core基礎 – 三等兵](http://d.hatena.ne.jp/sandai/20100823/p1#020)
>
> IE8からは大丈夫。その他のモダンブラウザはまずこんなことはない。

## 補遺

> * [JavaScriptのDOM Core基礎 – 三等兵](http://d.hatena.ne.jp/sandai/20100823/p1#020)
> * [Element Traversal API – 三等兵](http://d.hatena.ne.jp/sandai/20101220/p1)
[/markdown]