How to conditionally replace an element using RJS template

I have an RJS template that looks like this:

page.replace "id_#{}", :partial => "row"

But I only want it to execute if "id_#{}" is an element on the
current page?

something like:

if page.exists?("id_#{}")
  page.replace "id_#{}", :partial => "row"

I have read through every API page that I can find and can't find such
a beast? What would be the best way to do this?



not sure, but try this:

page << "if $('id_#{}') {"
page.replace "id_#{}", :partial => "row"
page << "}"

you can feed straight Javascripts into the page object with << (as
documented in the API), so i think it *should* work

Thanks for the pointer!

You were almost there, the solution was:

  page << "elem = $('id_(#{@foo}');"
  page << "if (elem) {"
    page.replace "id_(#{@foo}", :partial => "row"
  page << "}"

Needed the extra step.

Thanks :slight_smile:


You shouldn’t need an extra step. Just some brackets.

page << “if( $(’
id_#{}’) ){”
page.replace “id_#{}”, :partial => “row”

page << “}”

That should be the equivalent of what you had.