tyler tyler - 6 months ago 23
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

elements into a comma-delimited string. For example:

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

Should give

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();


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

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