0

I have a following HTML:

<div id="div1">
   <span class="icon"></span>
   <span class="text"></span>
</div>
<div id="div2">
   <span class="icon"></span>
   <span class="text"></span>
</div>
<div id="div3">
   <span class="icon"></span>
   <span class="text"></span>
</div>
<div id="div4">
   <span class="icon"></span>
   <span class="text"></span>
</div>

Then I have some business logic in JavaScript do decide what div elements to put in array:

var arr = [];
for(i = 1; i <= 4; i++) {
  if(someExpression) arr.push($("#div" + i));
}

The question: Is it possible to get all spans with class "text" from elements in arr (without using $(arr).each or for loop)?

I tried a simple things below, but they don't work..

$(arr).find(".text");
$(".text", $(arr));
$(".text", arr);

Thanks

2
  • 3
    Why are you putting jQuery objects into an array instead of a jQuery collection? Commented Dec 24, 2013 at 16:11
  • The example I showed is very simplified. Actually I work with angular directives and I manage the array of "$elements" in some helper service. Commented Dec 24, 2013 at 16:13

3 Answers 3

3

You can use a disguised loop :

var texts = arr.map(function(div){ return div.find('.text') });

Starting from your existing arr array, there's not really a way to avoid a kind of loop.

But note that it would simpler to do

var texts = $('#div1,#div2,#div3,#div4').find('.text');

or if you don't have other divs whose id starts with div :

var texts = $('[id^=div] .text');
Sign up to request clarification or add additional context in comments.

3 Comments

Ok, it looks like there no choice except of using some kind of loop. Thanks
@AlexDn What's the problem with loops ? Any time you do something there are a lot of hidden loops involved.
No problem with loops, just thought I can use the "hidden" jQuery loop instead of writing my own...
2

You have an array of jQuery objects, that's why you can't create a jQuery object from the array.

Put the elements in the array instead:

var arr = [];
for(i = 1; i <= 4; i++) {
  if(someExpression) arr.push($("#div" + i)[0]);
}

Then you can create a jQuery object from the array, and using find works fine to find the elements:

var texts = $(arr).find(".text");

Demo: http://jsfiddle.net/Guffa/Wu92L/

Comments

-1

why don't you just select all div.text?

var arr = $(".text");

2 Comments

It not helps me so much, you missed the point...I don't need all ".text", i need the text from specific divs only.
well, you need loops or in the wrost case, you can do it with recursion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.