HTML DOMドキュメントcreateAttribute()
例
// Create a class attribute:
const att = document.createAttribute("class");
// Set the value of the class attribute:
att.value = "democlass";
// Add the class attribute to the first h1:
const h1 = document.getElementsByTagName("H1")[0];
h1.setAttributeNode(att);
// Create a style attribute:
const att = document.createAttribute("style");
// Set the value of the style attribute:
att.value = "color:red";
// Add the style attribute to the first h1:
const h1 = document.getElementsByTagName("h1")[0];
h1.setAttributeNode(att);
以下のその他の例。
定義と使用法
このcreateAttribute()
メソッドは属性を作成し、その属性をAttrオブジェクトとして返します。
構文
document.createAttribute(name)
パラメーター
Parameter | Description |
name | Required. The name of the attribute to create. |
戻り値
タイプ | 説明 |
ノード | 作成された属性ノード。 |
その他の例
href = "www.w3schools.com"属性にアンカー要素を追加します。
// Create a href attribute:
const att = document.createAttribute("href");
// Set the value of the href attribute:
att.value = "https://www.w3schools.com";
// Add the href attribute to an element:
element.setAttributeNode(att);
ブラウザのサポート
document.createAttribute()
DOMレベル1(1998)の機能です。
すべてのブラウザで完全にサポートされています。
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |