要素のテキストコンテンツの取得と設定

要素とその子孫のテキストコンテンツを設定および取得するには、要素の textContent プロパティを使用します。

element.textContentCode language: CSS (css)

textContent は、すべてのHTMLタグを取り除いて返します。

次の例は、IDが container である要素のテキストコンテンツを返します。

const el = document.querySelector('#container');
console.log(el.textContent);Code language: JavaScript (javascript)

また、次の例は、コンテナ要素のテキストコンテンツを設定します。

const el = document.querySelector('#container');
el.textContent = 'Just simple text';Code language: JavaScript (javascript)

ほとんどの最新のWebブラウザは textContent プロパティをサポートしています。IE8は代わりに innerText を使用します。

WebアプリケーションがIE8をサポートしている場合は、次のコードを使用して要素のテキストコンテンツを取得できます。

const el = document.querySelector('#container');
const text = el.textContent || el.innerText;Code language: JavaScript (javascript)
このチュートリアルは役に立ちましたか?