How to return live list with jquery each

I’m trying to update the html content of a span element with the summation of some other spans with classes that can be toggled but the jQuery each() methods do not return the current list of checked items but is only set to the previous ones checked. My code below

function total() {
						var tot = parseInt($("#amount span").text(), 10);
						$(".green").each(function(){
							tot += parseInt($(this).html().trim().substr(1));
						});
						return tot;
					}

				$(".money").click(function() {
          $(this).toggleClass("green");
					// Update total amount
					$("#amount span").text(total());
			});

Markup can be found in this bin

You’re adding the amount(s) to the previous total, rather than replacing it. Try

var tot = 0;

instead.

1 Like

To my knowledge, jQuery cannot do this.

However, as you can use plain js even within jQuery functions, this is easily resolved.

document.getElementsByClassName() returns a live node list (querySelector does not, be careful there).

Good question, learned something new there:-)

:confused: :confused: :confused:

Thanks man. I love you already!! (no homo)

[quote=“nmeri17, post:1, topic:231665, full:true”]
I’m trying to update the html content of a span element with the summation of some other spans with classes that can be toggled but the jQuery each() methods do not return the current list of checked items but is only set to the previous ones checked.[/quote]

What is the expected behaviour?

For example:

  • when the first is one red and the second one is green
  • click on the red, which has two results:
    • the first one also turns green so that both are green
    • and both amounts are added to the total.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.