2016-09-13 10 views
2

私はnodeValueを使ってテキスト内のテキストを
element.firstChild.nodeValue = text
のように変更できますが、同じことをするにはsetAttributeを使用できますか?setAttributeを使用してテキストノード内のテキストを変更できますか?

HTML:

<p id="description">Some text here.</p> 

JS:

var description = document.getElementById("description"); 
description.setAttribute(nodeValue, text); 

それは動作しません。 "nodeValue"は要素の属性ではないことを意味しますか?あなたがあなたの代わりに.textContentを使用することができますので、ここではなくノード属性をノード内容を設定したい

答えて

2

setAttributeん、属性を設定してください。内容は設定しません。

ただし、コンテンツをコンテンツとして表示するには、CSSを使用できます。

var description = document.getElementById("description"); 
 
description.setAttribute('data-content', 'Updated text');
#description::after { 
 
    content: attr(data-content); 
 
}
<p id="description" data-content="Some text here."></p>

これが唯一の本当のコンテンツを挿入するのではなく、スタイリングの目的のために使用する必要があります。

0

// Set the text content: 
description.textContent = text; 

は、この情報がお役に立てば幸いです。

var description = document.getElementById("description"); 
 
var text = 'New text'; 
 

 
description.textContent = text;
<p id="description">Some text here.</p>

0

ありませんあなたがすることはできません。 setAttributeは、HTML要素の属性を操作するために使用されます。例えば

、あなたはあなたのようなものだろう無効にするボタンを更新したい場合:あなたはtextContentを使用する必要があるテキストを変更するには

var button = document.querySelector('my-button'); 
button.setAttribute('disabled', 'disabled'); 

を:

var description = document.getElementById("description"); 
description.textContent('New text here.'); 
関連する問題