Sam Munroe
Sam Munroe

Reputation: 1418

Selecting child of closest parent jquery

I have the following card header in my view:

<div class="card-header">
    <div class="media">
        <div class="media-body media-middle">
            <h4 class="card-title">{{ category.name }}</h4>
            <p class="card-subtitle">{{ category.description }}</p>
        </div>
        <div class="media-right media-middle">
            <a href="#" data-toggle="modal" data-target="#addForumPostModal" class="btn btn-white btn-sm add-post-button"><i class="material-icons">add</i></a>
        </div>
    </div>
</div>

I am trying to get the category name when I click on the add-post-button

I tried the following jquery but it just printed undefined:

$('.add-post-button').on('click', function (){
    console.log($(this).closest('media').children('card-title').html())
});

Upvotes: 2

Views: 3870

Answers (1)

nnnnnn
nnnnnn

Reputation: 150030

Use .find() instead of .children() - the latter only looks at immediate children, not grandchildren, etc., whereas .find() looks for descendants at any level.

Also, to select by class you need a '.' before the class name, so '.media' and '.card-title' rather than 'media' and 'card-title'.

$('.add-post-button').on('click', function (){
    console.log($(this).closest('.media').find('.card-title').html())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="card-header">
    <div class="media">
        <div class="media-body media-middle">
            <h4 class="card-title">{{ category.name }}</h4>
            <p class="card-subtitle">{{ category.description }}</p>
        </div>
        <div class="media-right media-middle">
            <a href="#" data-toggle="modal" data-target="#addForumPostModal" class="btn btn-white btn-sm add-post-button"><i class="material-icons">add</i></a>
        </div>
    </div>
</div>

Upvotes: 9

Related Questions