LoginSignup
2
1

More than 3 years have passed since last update.

Javascriptで全部のDOMにアクセスしたい時

Last updated at Posted at 2020-03-05

しょっちゅう書いてるのに忘れるからメモ
再帰的に処理するだけ

const getRecursionNodes = node => {
  node = node.firstChild;
  while (node) {
    getNodes(node);
    node = node.nextSibling;
  }
};

フレームワーク内で書いたら負け。
node.jsでスクレイピングしたい時とかにね

例えばこんなDOMっぽい文字列一部だけでもいいし全部でもいいし
axiosとかで普通に取得する。

const tagText = `
<div>
  <div>
    タイトル
    <span>サブタイトル</span>
  </div>
</div>
`;

で文字列をパースする

  const parser = new DOMParser();
  const doc = parser.parseFromString(tagText, 'text/html');
  getRecursionNodes(doc.getElementsByTagName('body')[0]);

こんな風に書くとgetRecursionNodesのwhile内で
body内の全要素をぶん回して処理できる。

parseFromStringはDOM Tree一部だけのつもりでも
htmlとbodyタグを勝手に付与しやがるので重複に注意。

空DOMをすっ飛ばしたい時はnextElementSiblingを使うと少し軽くなるかも。
この書き方だと文字列だけのnodeとかを処理したい時は
node.nodeTypeで判定してあげる必要がある。
https://developer.mozilla.org/ja/docs/Web/API/Node/nodeType

2
1
0

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
2
1