简体   繁体   中英

Unable to access descendant of an HTML element using jQuery

I have a problem with getting a html() value of child of a parent :D

 function voteup(e){ var count = $(e).parents('.item').children('.count'); console.log(count.html()); // undefined } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="post_contain"> <img src="images/comments/dQ6dz.jpg" alt=""> </div> <div class="item"> <p class="post-meta"> <span href="/gag/agVzE1g" target="_blank"> <span class="count">5</span>points </span> </p> <div class="vote"> <ul class="btn-vote left"> <li class="badge-item-vote-up-li"> <a onclick="voteup(this)">Click me</a> </li> </ul> </div> </div> 

In the function voteup(e) , I need to get the value of the class 'count', but I don't retrieve the value with html()

children only traverses a single level of the DOM tree - ie it won't find grandchildren.

Instead, use closest to find the .item -- which finds the single nearest match, as opposed to parents which can find multiple -- and find to locate the child, since that will traverse arbitrarily deep HTML structures:

function voteup(e){
    var count = $(e).closest('.item').find('.count');
    alert(count.html());
    var actual = parseInt(count.html(), 10);
    count.text(actual + 1);
}

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