0

I'd like to add together all of the data-score values in the <ul> and store them in a jQuery variable

The amount of <li> items would be dynamic

<ul id="score_list">
  <li data-score="1">FooBar</li>
  <li data-score="0">FooBar</li>
  <li data-score="0">FooBar</li>
  <li data-score="3">FooBar</li>
  <li data-score="1">FooBar</li>
</ul>

TIA

2
  • and what have you tried? Also, there's no thing as a jquery variable. Commented Mar 1, 2018 at 14:37
  • @AmitJoki, @connexo I did attempt to work it out but couldn't quite figure out how to loop through the <li> and add the total together. Didn't see the point in showing code that did not work. Apologies if I ruined your afternoon Commented Mar 1, 2018 at 15:00

1 Answer 1

1

It is as simple as iterating through all your li elements and getting data-score attributes value.

$(document).ready(function() {
    var x = 0;
    $('#score_list > li').each(function(a){
    x = x + +$(this).data('score')
  })
  console.log(x)
});

Below are things that you have checked before asking it:

Sign up to request clarification or add additional context in comments.

6 Comments

Questions not showing any effort whasoever should not be rewarded with an answer.
You should have checked it before downvoting. I adding a + before getting data-score. Please make sure to check answer correctly before downvoting
adding a + will convert a string to integer (parse it to integer) and then add it to x
I downvoted for answering. Getting an answer to a question like this will only encourage OP - and others - to find people coding stuff for them here.
Thank you for your working answer @G_S really appreciated! Apologies to everyone else if this was too simple to post - but hey, easy if you know the answer
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.