tags:

views:

5971

answers:

5

I know this is simple, but I can't wrap my head around it. Currently the following code returns "[object HTMLDivElement],[object HTMLDivElement]" I'd like it to return "div1,div2". Any thoughts? Thanks guys.

<HTML>
<HEAD>
<script type="text/javascript" src="path_to/prototype.js"></script>
<script>
function linkClick ()
{
    alert($$('div.basic'));
}
</script>
</HEAD>
<BODY>
   <div id="div1" class="basic" onclick="linkClick();"></div>
   <div id="div2" class="basic" onclick="linkClick();"></div>
</BODY>
</HTML>
+2  A: 
var ids = $$('div.basic').collect(function(el) { return el.id; }); //array of ids

alert(ids.join(','));

collect is another name for map, which is allows you to transform the elements one type of collection into another type by applying a "selector" function to each.

ifwdev
Just to be pedantic: you don't need the ".join(',')" part. Browsers seem to do automatically when alert()ing arrays, as the askers example shows.
Crescent Fresh
I was pretty sure of that but I figured I'd play it safe rather than post non working code. That and I was too lazy to check :)
ifwdev
+1  A: 
alert($$('div.basic').invoke('identify').join(',');

The invoke will call a function by name. The identify function will provide the id. When called on an array it will return an array of their ids. Join turns them into a string with commas in between.

Paulo
A: 

I had the same problem, there is a simple solution :

If varElement is your object containing a [HTMLDivElement] (or other DOM object) simply add '.id'

e.g.

varElement.id
Konrad
A: 

There's an optimization in prototype specifically for this:

$$('div.basic').pluck('id')

If I read your question right, you want a list of div IDs, rather than a string of ids separated by a comma.

Jarret Hardie
A: 

Konrad's solution works for me. It gets me the id, title, etc. (Wish I could vote 'up')

Filip Karnicki