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

-10

Using the shortest JS (ES5) code possible, as measured in number of characters, 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"

You cannot use ES6 or any libraries. The foobar elements will not ever be nested.

My current shortest solution is

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

Can anyone beat it?

tyler

Posted 2016-10-20T17:59:13.860

Reputation: 101

7Note that challenges that require answers to be in a specific language are generally discouraged. – Oliver Ni – 2016-10-20T18:05:42.260

2@Oliver although since this challenge is based on the DOM, an argument could be made for it being JS-only – Cyoce – 2016-10-20T18:17:32.597

2+"" saves 4 bytes over .join(). – Neil – 2016-10-20T18:22:50.103

You can remove the space in between document. and querySelectorAll. – Conor O'Brien – 2016-10-20T19:01:30.107

May I post a Python 2 solution just for the fun of it? I'll even flag it as non-competing :-) – ElPedro – 2016-10-20T19:21:07.747

@Oliver happy to make it language-independent, as long as the language can be parsed by all major browsers ;) – tyler – 2016-10-20T20:47:03.820

@Cyoke I take your point but should a good question really be that specific as to the technology to be used? There are plenty of other ways to manipulate HTML (admittedly most with external libraries) and it may have been more interesting to see how it was done in other languages and would probably have encouraged more answers. In my opinion it is not a bad challenge if it was more open and I have not downvoted. Maybe could have spent some time in the sandbox? (I didn't see it there but I may have missed it). – ElPedro – 2016-10-20T22:16:24.420

Answers

2

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

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

Hopefully someone can prove me wrong!

tyler

Posted 2016-10-20T17:59:13.860

Reputation: 101

1You can lose the semicolon at the end to save 1 – ElPedro – 2016-10-20T21:25:36.377

Of course -- just updated. Thanks! – tyler – 2016-10-20T21:58:04.637