HTML属性 – Dart逆引きリファレンス

2012.05.29

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

HTML属性(HTML attributes)

基本的には「Element」オブジェクトが持つ「attributes」プロパティを操作します。「attributes」プロパティは「AttributeMap」というインタフェース型のオブジェクトです。実体は「Map」インタフェースのデフォルトインスタンス(ただの連想配列)なので連想配列同様に扱います。

属性値を取得したい

オペレータ「[]」を使用して属性値にアクセスします。

Element element = new Element.html('<a href="http://www.dartlang.org/">Dart</a>');
document.query('#target').nodes.add(element);
element.attributes['href']; // http://www.dartlang.org/

属性に値を設定したい

オペレータ「[]=」を使用して属性値を設定します。

Element element = new Element.html('<a href="http://www.dartlang.org/">Dart</a>');
document.query('#target').nodes.add(element);
element.attributes['href'];
element.attributes['href'] = 'http://synonym.dartlang.org/';

要素から属性を除去したい

remove」メソッドを使用して属性を除去します。

Element element = new Element.html('<a href="http://www.dartlang.org/">Dart</a>');
document.query('#target').nodes.add(element);
element.attributes['href'];
element.attributes['href'] = 'http://synonym.dartlang.org/';
element.attributes.remove('href');

要素が指定した属性を持っているか知りたい

containsKey」メソッドを使用して属性マップに存在するかを調べます。
※Synonymでは「contains」メソッドとなっていますが「Map」には存在しないメソッドです。

Element element = new Element.html('<a href="http://www.dartlang.org/">Dart</a>');
document.query('#target').nodes.add(element);
element.attributes['href'];
element.attributes['href'] = 'http://synonym.dartlang.org/';
element.attributes.remove('href');
element.attributes.containsKey('href'); // false