Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Not only verbose, querySelectorAll returns a NodeList without normal array methods like map or forEach, so I find myself doing the following pretty much every time I use it:

  [...document.querySelectorAll('.example')]
Typically I see people create a utility function $ (querySelector) and $$ (querySelectorAll with conversion to array).

But this is fairly typical of the DOM API, some parts are awkwardly designed.



Hold your horses now, you can absolutely do:

document.querySelectorAll('.element').forEach(i => { yourFunction(i); });

I've not used map a whole lot, but I'm positive that it would work as well.


Oh you're right, there is a forEach method.

https://developer.mozilla.org/en-US/docs/Web/API/NodeList/fo...

    entries()
    forEach()
    item()
    keys()
    values()
And maybe values().map() will work too.


For what it’s worth, NodeLists do offer a forEach method (along with a few iterator returning methods which in contrast aren’t useful for concise style).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: