2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

DOMの子要素をchildNodesで取得しても配列処理できな時の対処法

Last updated at Posted at 2018-02-07

背景

DOMの子要素を取得して, 子要素の中にあるテキストを抜き出したかった.

問題

childNodesで子要素を取得してmapで処理しようとすると, mapは使えないといわれる.

const nodes = document.body.childNodes;
const texts = nodes.map(k=>k.querySelector("a").textContent) // map使えない
console.log(nodes)

原因

childNodesはNodelistというオブジェクトを返す.

console.log(nodes) //ex. Nodelist (4) [...]

対処法

Arrayに変換する.

  • ES6での表現
const nodes = [...document.body.childNodes]; // これで変換
  • 従来の表現
const nodes = document.body.childNodes;
const nodeList = Array.prototype.slice.apply(nodes) //これで変換

後はmap, reduce, など普通に使えるようになる.

jsnoteにサンプル載せました.
https://toyoharu-nishikawa.github.io/jsnote/#sample=sample/JavaScript/childNodes.js

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?