setAttribute
ドット ( .
) 属性表記の代わりに使用するベスト プラクティスは開発されていますか?
例えば:
myObj.setAttribute("className", "nameOfClass");
myObj.setAttribute("id", "someID");
また
myObj.className = "nameOfClass";
myObj.id = "someID";
setAttribute
ドット ( .
) 属性表記の代わりに使用するベスト プラクティスは開発されていますか?
例えば:
myObj.setAttribute("className", "nameOfClass");
myObj.setAttribute("id", "someID");
また
myObj.className = "nameOfClass";
myObj.id = "someID";
Javascript: The Definitive Guideから、それは物事を明確にします。HTML ドキュメントのHTMLElementオブジェクトは、すべての標準 HTML 属性に対応する JS プロパティを定義することに注意してください。
setAttribute
したがって、非標準属性にのみ使用する必要があります。
例:
node.className = 'test'; // works
node.frameborder = '0'; // doesn't work - non standard attribute
node.setAttribute('frameborder', '0'); // works
JavaScript でプログラムによるアクセスが必要な場合は、常に直接.attribute
形式を使用する必要があります (ただし、以下の quirksmode リンクを参照してください)。さまざまなタイプの属性 (「オンロード」と考えてください) を正しく処理する必要があります。
DOM をそのまま扱いたい場合はgetAttribute
/を使用します (例: リテラル テキストのみ)。setAttribute
ブラウザが異なると、この 2 つが混同されます。Quirks モード: attribute (in)compatibilityを参照してください。
.textContent
とに関連するさらに 2 つのポイントを追加します。.innerHTML
<div id="mydiv"></div>
var elem = document.getElementById("mydiv");
elem.textContent = "hello"; // OK - Content has been updated
elem.setAttribute("textContent", "hello"); // NOT OK - You are trying to set
// the attribute than it's content
elem.innerHTML = "world"; // OK - Content has been updated
elem.setAttribute("innerHTML", "world"); // NOT OK - You are trying to set
// the attribute than it's content
これは、setAttribute を使用したほうがよい 1 つのケースのように見えます。
var posElem = document.getElementById('animation');
var newStyle = 'background: ' + newBack + ';' +
'color: ' + newColor + ';' +
'border: ' + newBorder + ';';
if(typeof(posElem.style.cssText) != 'undefined') {
posElem.style.cssText = newStyle;
} else {
posElem.setAttribute('style', newStyle);
}