tyler tyler - 1 month ago 6
Javascript Question

Shortest possible JS code to get ids of all elements of a given tag

I want to gather all the ids on a page for

foobar
elements into a comma-delimited string. For example:

<div>
<foobar id="456"></foobar>
<foobar id="aaa"></foobar>
<foobar id="987"></foobar>
<div>


Should give
"456,aaa,987"


The
foobar
elements will not ever be nested, if that matters.

My current solution is

[].slice.call(document.getElementsByTagName("foobar")).map(function(a){return a.id}).join(","))


Is there a way to do this in pure JS with an even shorter (post-minification) statement?

Edit: In ES5 (aka "plain" javascript)

Edit 2: I was able to shave off a few characters with:

[].map.call(document.getElementsByTagName("foobar"),function(a){return a.id}).join();

Answer

I don't think it's going to get much shorter than this:

[].map.call(document.querySelectorAll("foobar"),function(a){return a.id})+"";
Comments