Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting .text() of children elements from jQuery()

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"
        )
)
like image 373
OpenCode Avatar asked Feb 11 '11 11:02

OpenCode


2 Answers

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);
like image 79
Kimtho6 Avatar answered Nov 02 '22 14:11

Kimtho6


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.

like image 29
BaggersIO Avatar answered Nov 02 '22 15:11

BaggersIO