javascript replaceWithでhtmlタグ要素を変更する

javascript replaceWithでhtmlタグ要素を変更する

javascriptで、replaceWithを使用して、htmlタグ要素を変更するサンプルコードを掲載してます。ブラウザはchromeを使用しています。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 100.0.4896.75

replaceWith使い方

「replaceWith」を使用すると、htmlタグ要素を変更することが可能です。

ノード.replaceWith

「replaceWith」使い方

<div id="main">
  text
</div>

<script>

'use strict';

const elm = document.getElementById("main");

const b = document.createElement("b"); // bタグを作成
const text = document.createTextNode("change"); // テキストを作成
b.appendChild(text); 

elm.replaceWith(b); // 変更

</script>

実行結果を見ると、要素が変更されているが確認できます。

また、以下のコードを、

const elm = document.getElementById("main");

elm.replaceWith(b);

document.getElementByIdの省略を使用して、簡潔に記述することもできます。

main.replaceWith(b);

サンプルコード

以下は、
「変更」ボタンをクリックして、html要素を変更する
サンプルコードとなります。

※cssには「tailwind」を使用して、アロー関数で関数は定義してます。

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

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
</head>

<script>

  window.onload = () => {

    btn.onclick = () => {      

      const b = document.createElement("b");
      const text = document.createTextNode("変更しました");
      b.appendChild(text);

      chg.replaceWith(b);
      
    };

  }

</script>

<body>
  <div class="container mx-auto my-56 w-64 px-4">

    <p id="chg">変更する要素</p>

    <div id="sample" class="flex flex-col justify-center">
      <button id="btn"
        class="bg-gradient-to-r from-blue-500 to-purple-700 hover:from-pink-500 hover:to-yellow-500 text-white py-2 px-4 rounded-full mb-3 mt-4">
         追加
      </button>
    </div>

  </div>
</body>

</html>

変更されていることが確認できます。