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

memo.

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

Contents

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

const url = document.getElementById('url');
console.log(url.href);
const p = document.getElementById('cap');
console.log(p.className);

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

getAttribute / setAttribute

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

const p = document.getElementById('cap');
console.log(p.getAttribute('class'));
const url = document.getElementById('url');
console.log(url.getAttribute('href'));
// 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/'

不特定の属性を取得する

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

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

IE8からは大丈夫。その他のモダンブラウザはまずこんなことはない。

補遺