ffxivguild ffxivguild - 5 months ago 8
jQuery Question

Setting var to a nested HTML elements text value

So I want to get the value of "nested" from "toplevel" and subtract it from "total". I'm sure my code is mega 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 I'm just missing something stupid!!!! Thanks in advance.

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

Answer

You forgot to add $ in the following code:

var cpcost = ('.nested');

Replace that with the following code should work:

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

To find .nested in the current clicked span (.toplevel), simply you can use $(this). By doing this you limit the query to the clicked element. Also, to find a specific element simply you can use find function in jQuery.