Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Access Closest p tag in jquery?

I'm having trouble with the .closest() method in jquery. Here is an example of my html and jquery that I am having trouble with.

Snippet of HTML ERB

<% @posts.each do |post| %>
  <tbody>
    <tr>
      <td><%= post.title %></td>
      <td><%= post.description %></td>
      <td><%= post.episodeNum %></td>
      <td><%= post.highDef %></td>
      <td>
        <%= link_to 'Show', post, :class => 'btn btn-info' %>
        <%= link_to 'Edit', edit_post_path(post), :class => 'btn btn-primary' %>
        <%= link_to 'Destroy', post, :class => 'btn btn-danger', confirm: 'Are you sure?', method: :delete %>
      </td>
      <td>
        <b>Votes: </b>
        <p class="current_vote"><font color=#1C1C1C>
          <%= post.upvotes.size - post.downvotes.size %>
        </p></font>
        <button type="button" class="buttonUp btn" id="<%= post.id %>">Increase Vote</button>
        <button type="button" class="buttonDown btn" id="<%= post.id %>">Decrease Vote</button>
      </td>
    </tr>
  <% end %>

Snippet of JQuery

$(document).ready(function() {
    $('.buttonUp').bind('click', function() {
        $.ajax({
            type: "POST",
            url: "/posts/increaseVote?id=" + $(this).attr("id"),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(data) {
                $(this).closest('p').text(data);
            }
        });
    });
    $('.buttonDown').bind('click', function() {
        $.ajax({
            type: "POST",
            url: "/posts/decreaseVote?id=" + $(this).attr("id"),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(data) {
                $(this).closest('p').text(data);
            }
        });
    });
});

Also, I am receiving my json correctly, in the case of my tests, my json data callbacksimply contains an integer.

like image 754
jab Avatar asked Sep 15 '25 13:09

jab


1 Answers

If p is the ancestor of the element use .closest();

If p is the sibling of the element use .siblings();

 $(this).closest('p').text(data);

 $(this).siblings('p').text(data);
like image 51
Sushanth -- Avatar answered Sep 18 '25 09:09

Sushanth --