简体   繁体   中英

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

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM