Tyler
Tyler

Reputation: 11499

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

Upvotes: 0

Views: 156

Answers (4)

Tyler
Tyler

Reputation: 11499

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

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

Upvotes: 0

lenilsondc
lenilsondc

Reputation: 9800

Shortest version that I found. I can't find a shorter than this without creating external helper functions. Anyway I think it won't help much.

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

Upvotes: 1

Axel M&#225;rquez
Axel M&#225;rquez

Reputation: 764

With ES5 I belive there is not much that can be done, however note that the default argument value for the join function is ',' so you can skip that and it will end up like:

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

With ES6 you can convert array-likes to arrays using Array.from, also you could use a lambda expression to shorten it even more.

So it will end up like:

Array.from(document.getElementsByTagName("div")).map(a => a.id).join()

Upvotes: 1

CroMagnon
CroMagnon

Reputation: 1208

Collects all 'foobar' and prints id values separated as you wanted.

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

<script>

var str = "";

var x = document.getElementsByTagName("foobar");

for(var i=0; i<x.length; i++){
	str = (str=="")?x[i].id:str+","+x[i].id;
}

console.log(str);
</script>

Upvotes: -1

Related Questions