ffxivguild ffxivguild - 1 year ago 85
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.


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

All put together is...
<div id = total>


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

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download