Paolo Di Pietro
Paolo Di Pietro

Reputation: 529

How to use a dynamic selector in JQuery

In a Ruby on Rails 6 environment, I need to hide all the html elements, and show only those having a specific id. But I am not able to correctly specify the selector, and the following xquery fragment doesn't run:

/* the @tag variable contains #xyz value */

$("#main-center .main-element").hide();

$(@tag).show();

I also tried Ruby interpolation $("#{@tag}") and $(<% @tag %>) with no success.

Anyone has a suggestion?

Upvotes: 0

Views: 54

Answers (2)

Nathan Hawks
Nathan Hawks

Reputation: 587

I'm not a Ruby guy but assuming Ruby is preprocessing this file before it hits the browser, I believe you need:

$("{@tag}").show();

Javascript needs the quotes because the selector is a string.

Upvotes: 0

Frank Fajardo
Frank Fajardo

Reputation: 7359

You have to enclose the selector in quotes (single or double):

$('<%= @tag %>').show();

or

$("<%= @tag %>").show();

Upvotes: 1

Related Questions