13

I'm having trouble to get the proper formatted texts of each child elements, either as an Array or in as text.

I had tried

var name= jQuery(".childOne").text();
var number = jQuery(".childTwo").text();

but it joins all the name/number text in name and number.

HTML is:

<span class="parent"><span class="childOne">David</span><span class="childTwo">541</span></span>
<span class="parent"><span class="childOne">Gruce</span><span class="childTwo">162</span></span>
<span class="parent"><span class="childOne">Proman</span><span class="childTwo">743</span></span>

and I need to generate output in multi-dim-array so that each child-element's-text can be figured out properly.

Preferred output can be in array or in any form.

Array
(
    0 = > array (
            0 => "David",
            1 => "541"
        ),
        
    1 = > array (
            0 => "Gruce",
            1 => "162"
        ),
        
    2 = > array (
            0 => "Proman",
            1 => "743"
        )
)
TylerH
  • 20,799
  • 66
  • 75
  • 101
OpenCode
  • 578
  • 1
  • 5
  • 12

4 Answers4

10

try this:

var data = [];

$('span.parent').each(function() {
    var $this = $(this);
    data.push({
        'name' : $this.find('span.childOne').text(),
        'number' : $this.find('span.childTwo').text()
    });
});

BTW: jQuery uses the Sizzle selctor engine. You should define the element type before the class, like span.parent. This is much more faster.

BaggersIO
  • 838
  • 7
  • 10
  • Another thing: If you access $(this) in the current scope more than once, you should use a seperate variable: like var $this. So, jQuery must not wrap the element twice, or more. – BaggersIO Feb 11 '11 at 11:48
  • @OpenCode: If you won't use the result literal, you can replace the push statement with the following code: data.push([$this.find('span.childOne').text(), $this.find('span.childTwo').text()]); – BaggersIO Feb 11 '11 at 12:55
3

If this is a fixed structure, you can do:

var data = [];

$('.parent').each(function() {
    data.push({
        'name': $(this).children('.childOne').text(),
        'number': $(this).children('.childTwo').text()
    });
});
TylerH
  • 20,799
  • 66
  • 75
  • 101
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
2

I have made a working example

var array= [];


$('.parent').each(function(index) {
   array.push({
        'name': $(this).children('.childOne').text(),
        'number': $(this).children('.childTwo').text()
    });
  });
alert(array[0].name);
Christian
  • 3,917
  • 2
  • 23
  • 40
Kimtho6
  • 6,154
  • 9
  • 40
  • 56
0
$('.parent').each(function(index) {
     alert($(this).find('.childOne').text());
     alert($(this).find('.childTwo').text());
  });

After you can put them into an array

alexl
  • 6,841
  • 3
  • 24
  • 29