いろんな方法でHello World!を表示する

これは2回目の投稿です。
Javascriptを使ったいろいろな方法で文字を表示してみます。

この投稿を後日、AIに相談してまとめ直しています。Javascriptでできるいろんな表示方法をよりスマートな方法で知りたい方はリンク先をご覧ください。サンプルも付けてあります。

<script>タグを使用して alert()を表示する

<!DOCTYPE html>
<html lang="ja">

<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Script-Type" content="text/javascript">
</head>

<body>
    <script>

        alert("Hello World!");
    
    </script>
</body>

</html>

実行結果


【非推奨】<script>タグを使用して document.write()を表示する

※HTMLの仕様上、document.write()を使うことは推奨されていないらしいです。むかしはよく見かけたんですけど。

<!DOCTYPE html>
<html lang="ja">

<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Script-Type" content="text/javascript">
</head>

<body>
    <div>
        <script>

            document.write("<h1>H1 : Hello World!</h1>");
            document.write("<h2>H2 : Hello World!</h2>");
            document.write("<h3>H3 : Hello World!</h3>");
            document.write("Hello World!");
        
        </script>
    </div>    
</body>

</html>

実行結果


<script>タグを使用して innerHTML()で書き換える

<!DOCTYPE html>
<html lang="ja">

<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Script-Type" content="text/javascript">
</head>

<body>
    <div>
        <p id="hello_area"></p>

        <script>
            const helloTxt = document.querySelector("#hello_area");
            helloTxt.innerHTML = "Hello World!";      
        </script>
        
    </div>    
</body>

</html>

実行結果


<script>タグを使用して insertAdjacentHTML()で追加する

第一引数に挿入場所が入ります。

  • beforebegin … 親要素の直前
  • afterbegin … 親要素内の先頭
  • beforebegin … 親要素内の末尾
  • afterend … 親要素の直後
<!DOCTYPE html>
<html lang="ja">

<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Script-Type" content="text/javascript">
</head>

<body>
    <div class="container">
        <!-- ここに追加される -->
    </div>   
    
    <script>
        const container = document.querySelector(".container");
        const newBrock = '<h1 class="brock">Hello World!</h1>';
        
        container.insertAdjacentHTML('afterend', newBrock);   
    </script>

</body>

</html>

実行結果


<script>タグと<canvas>タグを使用して描画する

描画されたテキストなのでマウスドラッグで選択することができないようです。

<!DOCTYPE html>
<html lang="ja">

<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Script-Type" content="text/javascript">
</head>

<body>
<canvas id="main"></canvas>

<script>

    const FONT = "48px monospace";
    const MyCanvas = document.getElementById('main');
    const MyContext = MyCanvas.getContext("2d");
    
    MyContext.font = FONT; 
    MyContext.fillText("Hello World!", 0, 50);

</script>

</body>

</html>

実行結果

By

Posted in