![](https://tech.mychma.com/wp-content/uploads/2022/05/hukidashi3_komaru-1.png)
文字列をスクリプトから出力するにはどうしたらいいですか?
![](https://tech.mychma.com/wp-content/uploads/2022/05/hukidashi1_normal.png)
![](https://tech.mychma.com/wp-content/uploads/2022/05/hukidashi1_normal.png)
![](https://tech.mychma.com/wp-content/uploads/2022/05/hukidashi1_normal.png)
textContentプロパティを利用すると場所も指定しながら文字列を出力することができます。
textContentを使って文字列を出力する
JavaScriptを使用してHTMLの文書内に文字列を出力するには、HTML要素のtextContent
プロパティを使用することができます。
textContent
プロパティは、HTML要素のテキストコンテンツを取得したり設定したりするために使用されます。
document.getElementById(指定ID).textContent = 文字列;
getElementById
は、HTML文書内で指定されたid
属性を持つ要素を取得するために使用されるJavaScriptの関数です。
次のサンプルでは、HTMLのp
要素にid
属性が設定されており、そのid
属性を使用して、JavaScriptでtextContent
プロパティを操作しています。
<!DOCTYPE html>
<html>
<body>
<h1>JavaScriptを使用した文字列の出力</h1>
<p id="demo">ここに文字列が出力されます。</p>
<script>
document.getElementById("demo").textContent = "Hello, World!";
</script>
</body>
</html>
上記の例では、HTML文書内のp要素を取得し、そのtextContent
プロパティに文字列を設定しています。HTMLページが読み込まれると、p要素に「Hello, World!」という文字列が出力されます。
![](https://tech.mychma.com/wp-content/uploads/2022/05/hukidashi3_nattoku.png)
![](https://tech.mychma.com/wp-content/uploads/2022/05/hukidashi3_nattoku.png)
![](https://tech.mychma.com/wp-content/uploads/2022/05/hukidashi3_nattoku.png)
指定したidの文字列を書き換えれるから表示位置は自由自在ってことですね!
textContent
プロパティは、HTML要素のテキストコンテンツを取得するときにも使用できます。次のようにして、HTML要素のテキストコンテンツを取得することができます。
var text = document.getElementById(“demo”).textContent;
アラートで文字列を出力する
window.alertメソッドを利用すると文字列をダイアログボックスを出して表示することができます。
window.alert(文字列);
<!DOCTYPE html>
<html>
<body>
<h1>JavaScriptを使用した文字列の出力</h1>
<script>
window.alert("Hello, World!");
</script>
</body>
</html>
コンソールに文字列を出力する
デバッグで文字列を出力したい場合はコンソールに出力することもできます。
JavaScriptのコンソールに文字列を出力するには、console.log()
関数を使用します。
この方法では、Webブラウザの開発者ツールのコンソールタブで文字列を確認することができます。
<!DOCTYPE html>
<html>
<body>
<h1>JavaScriptを使用した文字列の出力</h1>
<script>
console.log("Hello, World!");
</script>
</body>
</html>
![](https://tech.mychma.com/wp-content/uploads/2023/01/image-7.png)
![](https://tech.mychma.com/wp-content/uploads/2023/01/image-7.png)
「文字列を出力する方法」のまとめ
JavaScriptの「文字列を出力する方法」のまとめです。
- HTML要素の
textContent
プロパティを設定することで、HTML要素に文字列を設定、取得することができます。 alert()
関数を使用すると、HTMLの文書内にスクリプトを記述して、文字列をダイアログボックスで表示することができます。console.log()
関数を使用すると、JavaScriptのコンソールに文字列を出力することができます。
HTML要素のtextContent
プロパティ、alert()
関数やconsole.log()
関数を使用することで、HTMLの文書内に文字列を出力することができます。
コメント