mike thomson mike thomson - 1 year ago 59
Javascript Question

Unable to access descendant of an HTML element using jQuery

I have a problem with getting a

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 class="item">
<p class="post-meta">
<span href="/gag/agVzE1g" target="_blank">
<span class="count">5</span>points
<div class="vote">
<ul class="btn-vote left">
<li class="badge-item-vote-up-li">
<a onclick="voteup(this)">Click me</a>

In the function
, I need to get the value of the class 'count', but I don't retrieve the value with

Answer Source

children only traverses a single level of the DOM tree - i.e. 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');
    var actual = parseInt(count.html(), 10);
    count.text(actual + 1);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download