user2571510
user2571510

Reputation: 11377

jQuery methods closest and parent / find not working on certain div

I have a div with the following content:

My HTML:

<div class="panel-footer">
    Cat1: <span class="badge">5</span>&nbsp;&nbsp;
    Cat2: <span class="badge">3</span>&nbsp;&nbsp;
    <a href="javascript:void(0)" class="viewComments">Comments:</a> <span class="badge cntComments">2</span>
    <span class="pull-right">
        <button class="btn btn-default btn-xs">Delete</button>&nbsp;&nbsp;
        <button class="btn btn-default btn-xs">Add</button>
    </span>
</div>

I am trying to get the text of the span with class "cntComments" using jQuery (so in this case it should return "2") but when I alert this out it always shows me a blank alert. I also tried using "parent()" instead of "closest()" but that didn't work either.

What am I doing wrong here?

My jQuery:

$(document).on('click', '.viewComments', function() {
    var cntComments = $(this).closest('div.panel-footer').find('cntComments').text();
    alert(cntComments);
    // ...
});

Upvotes: 0

Views: 2117

Answers (2)

Milind Anantwar
Milind Anantwar

Reputation: 82241

You are missing class selector . in find method:

var cntComments = $(this).closest('div.panel-footer').find('.cntComments').text();

Working Demo

Upvotes: 1

Umesh Sehta
Umesh Sehta

Reputation: 10683

change .find('cntComments') to .find('.cntComments') you forgot . class selector

$(document).on('click', '.viewComments', function() {
var cntComments = $(this).closest('div.panel-footer').find('.cntComments').text();
alert(cntComments);
// ...
});

Demo

Upvotes: 1

Related Questions