Rails‎ > ‎

Rails - Checking if an HTML element exists in RJS

RJS doesn't really let you check if an HTML element exists (unlike javascript that has getElementById == null ) .

So there are 2 ways of implementing that.


Method 1

You can simply write javascript in the RJS template as follows

page << "if ($('current_item') != undefined){"

page[:current_item].visual_effect :highlight,:startcolor => "#88ff88" ,:endcolor => "#114411"


page <<"}"


In this example I check if 'current_item' exists, and then I highlight it.

Method 2

You can iterate over CSS parameters (including ID) and so if the element doesn't exist - the iteration is empty.

page.select("div#notice" ).each { |div| div.hide }

In this example I hide the "notice" div (all notice divs)
Comments