Convert List like into List
document.querySelectorAll(".dir-item").map((item) => item.innerText)
The error document.querySelectorAll(...).map is not a function
occurs because querySelectorAll
returns a NodeList
, which is not an Array and does not have the map
method. To solve this, you can convert the NodeList
to an Array using one of the following methods:
- Spread Operator
const items = [...document.querySelectorAll(".dir-item")]
const itemTexts = items.map((item) => item.innerText)
- Array.from()
const items = Array.from(document.querySelectorAll(".dir-item"))
const itemTexts = items.map((item) => item.innerText)
- Array.prototype.slice.call()
const items = Array.prototype.slice.call(document.querySelectorAll(".dir-item"))
const itemTexts = items.map((item) => item.innerText)
After converting the NodeList
to an Array, you can then use the map
method to get the innerText
of each element.
Here’s an example using the spread operator:
const itemTexts = [...document.querySelectorAll(".dir-item")].map((item) => item.innerText)
console.log(itemTexts)
This will give you an array of the text content of each element with the class dir-item
.