Seetha Raman
Seetha Raman

Reputation: 145

jquery each function to get the class value content

script

$("#activities").next().next().each(function(i) { });

html

<div class="head" id="activities" >Activities</div>
<div class="sub-head"> <span class="title">Activity</span> <span class="value">Min</span> <span class="unit">Calories</span> </div>
<div class="rows"> <span class="title">bicycling</span> <span class="value">30</span> <span class="unit">174</span> </div>
<div class="rows"> <span class="title">fishing and hunting</span> <span class="value">30</span> <span class="unit">261</span> </div>
<div class="rows"> <span class="title">transportation</span> <span class="value">30</span> <span class="unit">261</span> </div>
<div id="activitiesData"></div>

can anybody please help me to get datas from this div using each in jquery?

Upvotes: 3

Views: 14464

Answers (4)

Carls Jr.
Carls Jr.

Reputation: 3078

Please check here for the solution.

$('#GetTitles').click(function(){
    $('div.rows .title').each(function(){
        alert($(this).text());
    });
});

JSFiddle Sample Solution

Upvotes: 2

Alnitak
Alnitak

Reputation: 339816

This should do it:

var sum = 0;
$('#activities').nextAll('.rows').find('.value').each(function() {
    var n = parseInt($(this).text(), 10); 
    if (!isNaN(n)) sum += n; 
});

Upvotes: 4

Ram
Ram

Reputation: 144689

you can select .rows elements directly instead of traversing the DOM by using multiple next() methods, try the following:

var sum = 0;  
$(".rows .value").each(function(){
       var val = parseInt($(this).text(), 10)
       if (!isNaN(val)) {
            sum += val
       }          
})   

DEMO

Upvotes: 4

adeneo
adeneo

Reputation: 318192

To get each individual value in an array:

var values = $(".value", ".rows").map(function(i, e) {
    return parseInt(e.innerHTML, 10);
})​;

FIDDLE

To get the combined sum of the values

var value = 0;
$.each($(".value", ".rows"), function(i,e) {
    value += parseInt(e.innerHTML, 10);
});

FIDDLE

Upvotes: 1

Related Questions