# RJS Chaining Problem

**URL:** <https://www.ruby-forum.com/t/rjs-chaining-problem/174977>\
**Category:** Rails\
**Created:** [September 5, 2009, 3:55am UTC](https://www.ruby-forum.com/t/rjs-chaining-problem/174977 "2009-09-05T03:55:21Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![bob](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/ea666f/32.png) [@bob](https://www.ruby-forum.com/u/bob)\
**Post date:** [September 5, 2009, 3:55am UTC](https://www.ruby-forum.com/t/rjs-chaining-problem/174977/1 "2009-09-05T03:55:21Z")

</div>

Hi,

I am having a problem with the way RJS generates code. Say I have  
html like this:

```
<div id="parent">
  <div id="child1"></div>
  <div id="child2"></div>
</div>

```

and RJS code like this:

```
parent = page["parent"]
parent.down('#child1').highlight
parent.down('#child2').highlight

```

the generated JS code becomes:

```
$("1").down("#a").highlight().down("#b").highlight();

```

which is incorrect, because the second down() starts from within  
#child1, whereas it should have started from within #parent.

By not declaring the “parent” variable and use page[“parent”] for  
every highlight() call it would work, but it’s not very DRY. I could  
also append a bunch of up() and down() in a long chain, but the code  
gets messy difficult to follow.

I was wondering if there are any good ways to generate code that are  
correct, clean, and DRY?

Thanks in advance!

Bob

---

<div class="post-metadata">

**Author:** ![bob](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/ea666f/32.png) [@bob](https://www.ruby-forum.com/u/bob)\
**Post date:** [September 5, 2009, 7:31pm UTC](https://www.ruby-forum.com/t/rjs-chaining-problem/174977/2 "2009-09-05T19:31:24Z")

</div>

Hi Bob,

On Fri, 2009-09-04 at 18:53 -0700, bob wrote:

> ```
> parent = page["parent"]
> 
> ```
> 
> By not declaring the “parent” variable  
> I think maybe the problem you’re having results from declaring a  
> variable, and perhaps naming a DOM element, ‘parent’. parent is a  
> Javascript property; as in:

window.parent

Try using a different name and see if the problem persists.

HTH,  
Bill

---

<div class="post-metadata">

**Author:** ![bob](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/ea666f/32.png) [@bob](https://www.ruby-forum.com/u/bob)\
**Post date:** [September 6, 2009, 12:01am UTC](https://www.ruby-forum.com/t/rjs-chaining-problem/174977/3 "2009-09-06T00:01:17Z")

</div>

Oh, actually it’s just a simplified example code to focus on the  
concept. The problem is that when I use a ruby variable containing an  
element multiple times, RJS chains them together while disregarding  
the traversal methods, which generates incorrect code.
