最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Selecting child of closest parent jquery - Stack Overflow

programmeradmin0浏览0评论

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

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())
});
Share Improve this question asked Apr 4, 2017 at 2:35 Sam MunroeSam Munroe 1,4182 gold badges23 silver badges45 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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./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>

发布评论

评论列表(0)

  1. 暂无评论