views:

54

answers:

1

In Rails' RJS Adapter,

page['id'] // $('id')

accesses an CSS-id,

page['id'].property // $('id').property

a property of it. But how can I access an array index, e.g.

page.select('ul').value_at(2) // $('id').select('ul')[2]

Is there any way of doing this without writing:

page << "$('id').select('ul')[2]"
+2  A: 

You can't access arrays like that from rjs but, anyone of these would work:

page['id']['firstChild']['nextSibling']
page['id'].down(2)

Generates:

$("id").firstChild.nextSibling;
$("id").down(2);

Of course, the best solution would be to add some identifying css class or element id to the second element and select by that from your rjs file.

If you'd like to stick to using page.select, you could implement value_at like this (called pick here):

>>> Array.prototype.pick = function(n) { return this[n]; };
function()
>>> ['a', 'b', 'c'].pick(1)
"b"
jdeseno
Great ways of avoiding this problem! I still can't believe that this rather basic syntax isn't covered, but ok. ((Little remark: 2 is the third child, so it should read `['firstChild']['nextSibling']['nextSibling']`, shouldn't it?)
giraff
An identifying class don't solve this problem, as it generates another Array.
giraff
Sorry, you'd need to add an id. I've edited my answer with an implementation of 'value_at' you could include in your js file to do things your way.
jdeseno
Oh, wow, I thought I had to do it in Rails, but this does the trick. Thanks!
giraff