JavaScriptでテキストを一文字ずつspanタグで囲む方法

一文字ずつフェードインさせたい場合などで一文字ずつspanタグで囲むことがあるが、これを一文字ずつ手作業でやるのは面倒なので、JavaScriptを使って処理する。

<p class="js-text">サンプルテキスト</p>
// 対象の要素を取得
const paragraph = document.querySelector(".js-text");

// テキストコンテンツを取得
const textContent = paragraph.textContent;

// テキストコンテンツを一文字ずつ分割して<span>タグで囲んで新しい文字列を作成
const newTextContent = [...textContent]
  .map((char) => `<span>${char}</span>`)
  .join("");

// 新しい文字列をHTMLに挿入
paragraph.innerHTML = newTextContent;

関数を使用した記述は以下の通り。

// 文字列内の各文字を<span>タグで囲む関数
const newTextContent = function (str) {
  // 文字列を分割し、各文字を<span>タグで囲み、結合して返す
  return [...str].map((char) => `<span>${char}</span>`).join("");
};

// 対象の要素を取得
const paragraph = document.querySelector(".js-text");

// 要素の内容をwrapCharSpan関数の実行結果で置き換える
paragraph.innerHTML = newTextContent(paragraph.textContent);
inserted by FC2 system