3

I am using the $.find() method in jQuery and i am not able to get all the results which match the selector condition.

This is my HTML

<div class="something">
<label> Hello </label>
<div class="selse">
    <label> Hi </label>
    <label class="imp"> This is </label>
    <label class="imp"> Nooo </label>
</div>
<label class="imp"> Sparta </label>
<label class="imp"> Right ? </label>
</div>

<div class="something">
<label> Hell No </label>
<div class="selse">
    <label> Hi </label>
    <label class="imp"> Cant </label>
</div>
<label class="imp"> touch </label>
<label class="imp"> this </label>
 <label class="imp"> MC  </label>
</div>​

So when i do the following JS

$("div.something").each(function(index) {
   alert(index + ': ' + $(this).find("label.imp").html())
    });​

I expected that it'll give me 2 alerts . One with 0. This is, Nooo, Sparta, Right ? and the other with 1. Cant, touch, this, MC . But i got just 0. This is and 1. Cant .

I tried using arrays in the same function like this

$("div.something").each(function(index) {
    var arr=[]
    arr = $(this).find("label.cidForm").html();
    alert(arr);
    });​

No i get alert boxes with 'Undefined' in them. What am i doing wrong in both these cases ? I just want an array with all the values inside label.imp elements.

Here's a JSFiddle i put up for the same. http://jsfiddle.net/WPeKF/1/

Pradep
  • 1,874
  • 5
  • 21
  • 31

2 Answers2

11

.html() and other getter methods only return the value of the first matched element. With that in mind, i think you can figure out the logic changes that need to be made.

Fiddle: http://jsfiddle.net/WPeKF/2/

Code:

var arr = $("div.something").map(function(){
    return $(this).find("label.imp").map(function(){
        return $(this).html();
    }).get().join("");        
}).get();
console.log(arr);
Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • Oh. I was concentrating only on the find() method. Thanks for the info. – Pradep Nov 07 '12 at 22:03
  • 1
    The only purpose of the nested map is to join the strings of the divs within each something div into one string. For comparison, http://jsfiddle.net/WPeKF/3/ – Kevin B Nov 07 '12 at 22:06
0

This should do the trick:

var myArray = $("div.something label.imp").map(function(index) {
    return $(this).html();
});​
Shmiddty
  • 13,847
  • 1
  • 35
  • 52
  • That insert any `.imp` into a single array. But you need to have a parent array, that stores each `.something` (arrays of `.imp`). – feeela Nov 07 '12 at 23:47