mike thomson
mike thomson

Reputation: 57

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

Upvotes: 0

Views: 65

Answers (1)

nbrooks
nbrooks

Reputation: 18233

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');
    alert(count.html());
    var actual = parseInt(count.html(), 10);
    count.text(actual + 1);
}

Upvotes: 3

Related Questions