LoginSignup
0
0

More than 1 year has passed since last update.

あるHTML要素配下のテキストを一文字ずつ抽出する

Posted at

body内に書かれているテキストをJavaScriptで一文字ずつ取得したい!!!というニッチな要望に応える記事です。

たとえば?

<html>
    <head>
        <title>たとえば?</title>
    </head>
    <body>
        たとえばこのように素のテキストや
        <div>
            いろんな要素が
            <p>入れ子になっている<span></span></p>
            特定の要素配下のテキストをすべて取得して
        </div>
        <div>
            一文字ずつ
            <p>"た" "と" "え" "ば" "こ" "の" ...</p>
            と出力したい</br>
            みたいな話です。
        </div>
    </body>
</html>

実装コードと出力結果

コード

//parent自身と自身の配下にあるノードすべてにcallbackをさせる
const makeChildrenToDo = (parent, callback) => {
    const children = parent.childNodes;
    //直下の子要素にこの関数を再帰的に適用する
    children.forEach((child) => {
        makeChildrenToDo(child, callback);
    });
    callback(parent);
}
//element直下にあるテキストを一文字ずつ出力する
const logText = (element) => {
    const nodeValue = element.nodeValue;
    //elementがnodeとしては#textであり、truthyであり、空白文字ではない
    if (element.nodeName === "#text" && nodeValue && nodeValue.match(/\S/g)) {
        const characters = Array.from(nodeValue);
        characters.map((chara) => {
            //charaがtruthyであり、空白文字でない
            if (chara && chara.match(/\S/g)) {
                console.log(chara);
            }
        });
    }
}
const main = () => {
    makeChildrenToDo(document.body, logText);
}
window.onload = main;

コードをheadに入れて読み込んだ時の出力結果

た
と
え
ば
こ
の
(略)
話
で
す
。

body内のテキストが一文字ずつ出力される。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0