Setting var to the text value of nested HTML elements

So, I want to get the value "nested" from "toplevel" and subtract it from "total". I'm sure my code is very inefficient, forgive me.

HTML:

  <span class="toplevel"> 
    Clickable
    <span class="nested"> 50 </span>
</span> <br>

All put together is...
<div id="total">
  9999
</div>

JS:

$(document).ready(function() {
  var totalcp = parseInt("9999", 10);
  $('#total').text(totalcp).toString();
  $('.toplevel').click(function() {
      var cpcost = ('.nested');
    totalcp = totalcp - cpcost; 
    $('#total').text(totalcp).toString();
  });
});

My main problem is the line:

var cpcost = ('.nested');

I know that I'm just missing something stupid !!!! Thanks in advance.

Codepen link - from the above combination, the problem again is that var cpcost does not get a "nested" value. If replaced with a flat number, it works great.

+4
source share
1 answer

You forgot to add $to the following code:

var cpcost = ('.nested');

Replace this with the following code:

var cpcost =parseInt( $(this).find('.nested').text() );

.nested - (.toplevel), $(this). , , . , , find jQuery.

+3

All Articles