Search code examples
javascriptjqueryparentclosest

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())
});

Solution

  • 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>