Thibaud Clement
Thibaud Clement

Reputation: 6897

Rails 4: select DOM element with dynamically generated id

In my Rails 4 app, I have the following DOM structure on one of my views:

<tr id="post_row_<%= post.id%>">
  [...] # Truncated for brivety
  <td class="cell_content_center post_approval_section">
    [...] # Truncated for brivety
  </td>
</tr>

I need to update the content of the td with JavaScript.

In order to select it, I tried:

$('tr#post_row_<%= j post.id %> > td.post_approval_section').html('<%= j render(partial: "calendars/post_approval") %>');

but this gives me an error:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

As you can see, the id of the parent tr is dynamically generated.

How can I select it with JavaScript?

Upvotes: 0

Views: 151

Answers (3)

user3506853
user3506853

Reputation: 814

This code snippet will find the tr with id="post_row_<%= j post.id %>". Then inside tr, it will find td with class="post_approval_section".

$("tr#post_row_<%= j post.id %>").find('td.post_approval_section');

Upvotes: 0

user3506853
user3506853

Reputation: 814

Use double quotation(" ") instead of single quotes(' ') like:-

$("tr#post_row_<%= j post.id %> > td.post_approval_section")

Upvotes: 2

bo-oz
bo-oz

Reputation: 2872

Use double " and #{} notation:

$("tr#post_row_#{post.id} td.post_approval_section")

Upvotes: 0

Related Questions