learningtech
learningtech

Reputation: 33695

jquery to update all elements after nth element?

Let's say I have the following code:

<ul>
    <li data-val="1">1</li>
    <li data-val="4">2</li>
    <li data-val="2">3</li>
    <li data-val="5">4</li>
    <li data-val="1">5</li>
</ul>

I want all items that are ul li:gt(0) to have a innerHTML with the sum of data-val + innerHTML. So the result I want is:

<ul>
    <li data-val="1">1</li>
    <li data-val="4">6</li>
    <li data-val="2">5</li>
    <li data-val="5">9</li>
    <li data-val="1">6</li>
</ul>

I could use a for loop to do this, but not sure if that's the best way in terms of performance and in terms of minimally verbose code. Is there a better way?

I can use jquery and css.

Upvotes: 0

Views: 114

Answers (1)

Richard Dalton
Richard Dalton

Reputation: 35793

You can call .html() and pass a function which sums the two fields:

$('ul li:gt(0)').html(function() {        
    return $(this).data('val') + parseInt($(this).html());
});​

http://jsfiddle.net/infernalbadger/VJAza/

Upvotes: 2

Related Questions