r/javascript • • Mar 18 '19

What's your favorite, most useful javascript one-liner?

385 Upvotes

422 comments sorted by

View all comments

Show parent comments

2

u/[deleted] Mar 19 '19

NodeLists do not have the Array functions on their prototype.

[].forEach.call(document.querySelectorAll('.whateverClassTheCheckboxHas'), cb => cb.click());

33

u/AwesomeInPerson Mar 19 '19

NodeList actually implements forEach(), with decent browser support. :)

12

u/anlumo Mar 19 '19

Hmm map doesn't work here in Chrome, but forEach does.

17

u/[deleted] Mar 19 '19

Oh, hey. Looks like forEach has been added to the WebIDL spec for NodeList and other DOM iterables. Ain't that fancy. Time to go revise a whole bunch of code!

11

u/the_argus Mar 19 '19

Can also use Array.from(document...).forEach(...)

13

u/BabyLegsDeadpool Mar 19 '19

Or just do [...document.querySelectorAll(...)].forEach(...)

8

u/Sn34kyMofo Mar 19 '19

Or, if you're in Chrome, use $$(), which is a console method that returns the result of querySelectorAll() as an array instead of a nodelist! Very succinct and handy when futzing with the DOM in DevTools.

Example: $$('.some-class').forEach(...);

1

u/fucking_passwords Mar 19 '19

But, NodeList has forEach... if you example used map or reduce it would make more sense

1

u/Sn34kyMofo Mar 19 '19

Indeed. My reply was simply meant to contribute, not dispute. Pick any other array-only method to use with my example instead. =)

0

u/enHello Mar 19 '19

Or [].slice.call(document.querySelectorAll(...)).map(node => node.foo)

1

u/alinnert Mar 19 '19

Yeah, this is the pre-ES6 version. I used it a lot when I had to. It's just not as clear about what it's doing.

1

u/enHello Mar 19 '19

Agreed.

0

u/[deleted] Mar 19 '19

[deleted]

1

u/[deleted] Mar 19 '19

It does not. The Chrome command line API comes with $, which is not available from browser code. Also, the CLA version of $ is equivalent to document.querySelector, not querySelectorAll.

3

u/[deleted] Mar 19 '19

Dev-tools is the context of the conversation

2

u/Sn34kyMofo Mar 19 '19

$$ is querySelectorAll in DevTools, except it returns the nodelist as an array, which is nice.

Example: $$('.ad-container').slice(-1)[0].remove();