JavaScript textContentプロパティを利用するサンプル

環境
Google Chrome 111.0.5563.65
Windows 10 Home 64bit

書式
const 変数名 = document.getElementById(“ID名");
変数名.textContent = “htmlタグ";
textContent は Node のプロパティで、ノードおよびその子孫のテキストの内容を表します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<body>
<p id="pA">表示ボタンを押して下さい</p>
<input type="button" value="表示" onclick="funA()">
<script>
function funA(){
const pA = document.getElementById("pA");
pA.textContent = "<b>表示ボタンを押しました</b>";
}
</script>
</body>
</html>
<!DOCTYPE html> <html> <body> <p id="pA">表示ボタンを押して下さい</p> <input type="button" value="表示" onclick="funA()"> <script> function funA(){ const pA = document.getElementById("pA"); pA.textContent = "<b>表示ボタンを押しました</b>"; } </script> </body> </html>
<!DOCTYPE html>
<html>
<body>

<p id="pA">表示ボタンを押して下さい</p>
<input type="button" value="表示" onclick="funA()">

<script>
function funA(){
      const pA = document.getElementById("pA");

      pA.textContent = "<b>表示ボタンを押しました</b>";
}

</script>

</body>
</html>

実行結果
「表示」ボタンを押すと、textContentプロパティは、htmlのタグを文字「<b>表示ボタンを押しました</b>」としてそのまま出力します。

 

JavaScript

Posted by arkgame