「JavaScript」textContentプロパティでhtml文字列を含まれないテキストを設定する方法

環境
Google Chrome 102.0.5005.63

書式
element.textContent = “設定する文字列”
textContentプロパティを使用して、HTML文字列を含まない文字列のテキストを取得します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<body>
<div id="txtshow">test abc
</div><br>
<input type="button" value="変更" onclick="funA()">
<script>
function funA(){
//要素への参照を取得する
var txtMsg = document.getElementById('txtshow');
txtMsg.textContent = "study skill become smart";
}
</script>
</body>
</html>
<!DOCTYPE html> <html> <body> <div id="txtshow">test abc </div><br> <input type="button" value="変更" onclick="funA()"> <script> function funA(){ //要素への参照を取得する var txtMsg = document.getElementById('txtshow'); txtMsg.textContent = "study skill become smart"; } </script> </body> </html>
<!DOCTYPE html>
<html>
<body>
<div id="txtshow">test abc
</div><br>
<input type="button" value="変更" onclick="funA()">
<script>
function funA(){
   //要素への参照を取得する
  var txtMsg = document.getElementById('txtshow');
  txtMsg.textContent = "study skill become smart";
}
</script>

</body>
</html>

実行結果
「変更」ボタンを押下すると、div要素(id=txtshow)に設定されている文字列を変更します。

JavaScript

Posted by arkgame