sharataka
sharataka

Reputation: 5132

How to find a class within a div id using jquery?

When the user click the like button, I am trying to capture the number in the class 'badge'. Here's what I have in my JS so far where I find the div id containing the elements but I'm having trouble going down and finding .badge within this div:

//Like annotation JS
  $('.liking').click(function (e){
  e.preventDefault();
  div = $(this).closest('div').attr('id');
  console.log(div);

})
//End of liking annotation JS


<div id = 'div1'>
<% @annotations.each do |annotation| %>
    <p><strong>Name</strong>
    <p class = 'lead' style = 'font-size: 14px; line-height: 23px;'>
        <%= annotation.annotation %>
    </p>
    <p>
        <small>
            <span class = 'badge' style = 'font-size: 12px;'>0</span> &nbsp;
            <a href = "#" class = 'liking'>
                Like
            </a>
        </small>
    </p>
    <hr class="featurette-divider" style = 'margin:15px;'>
<% end %> <!-- End of verse annotations -->
</div>

Upvotes: 1

Views: 610

Answers (6)

Neeraj
Neeraj

Reputation: 4489

Try This Code

$('.liking').click(function (e){
e.preventDefault()
var div1 =  $(this).closest('div').find('.badge'); 
alert(div1.text());

})

See Demo

Upvotes: 1

rahul maindargi
rahul maindargi

Reputation: 5655

Tried this?

$('.liking').click(function (e){
  e.preventDefault();
  div = $(this).closest('div').find('.badge');
  console.log(div);

})

here is working link http://jsfiddle.net/ASN7c/

Upvotes: 1

Konstantin Dinev
Konstantin Dinev

Reputation: 34915

Try this code:

var text = $(this).siblings('span.badge').text();
var number = parseInt(text, 10);

Upvotes: 1

Barmar
Barmar

Reputation: 782529

badge = $(this).closest('div').find('.badge');

But in your HTML, badge is always right before liking, so you can do:

badge = $(this).siblings('.badge');

Upvotes: 1

Chris Dixon
Chris Dixon

Reputation: 9167

Will .badge always be the parent element of the .liking link?

If so, you can simply do:

 $('.liking').click(function (e){
  e.preventDefault();
  var $badge = $(this).prev();
  console.log($badge.text());
})

Check out http://jsfiddle.net/2c9xz/

Upvotes: 0

Ram
Ram

Reputation: 144729

You don't necessarily need the ID, you can use the find method, you can also use siblings method.

$('.liking').click(function (e){
  e.preventDefault();
  var $badge = $(this).closest('div').find('.badge');      
  // var $badge = $(this).siblings('.badge');
  console.log($badge.text());
})

Upvotes: 1

Related Questions