2

The project I am working has many of the same kind of element on a page. This kind of element contains some text that I need to store in an array. I can easily select all these elements with JQuery and have JQuery return a result set of elements. However, I am having a really difficult understanding how to iterate through all of the elements in the result set and storing the text from each element in an array.

I was thinking maybe using something like foreach somehow?

I appreciate any help in this regard.

Many thanks in advance!

HTML

<div class="option">apples</div>
<div class="option">oranges</div>
<div class="option">peaches</div>
<div class="option">grapes</div>

JavaScript

var i = 0;
foreach($('.option').text() as x){
    someArray[i] = x;
    i++;
}

Desired Output

alert(someArray[0]); // apples
alert(someArray[1]); // oranges
alert(someArray[2]); // peaches
alert(someArray[3]); // grapes
1

2 Answers 2

4

you can use $.each to iterate over the elements.

var arr = [];
$('.option').each(function() {
    arr.push( $(this).text() );
});

console.log(arr.join());

Check Fiddle

You can also use the .map method

var arr = $('.option').map(function () {
    return this.innerHTML
}).get().join();

console.log(arr);
Sign up to request clarification or add additional context in comments.

Comments

0

You can use for

var options = $('.option'),
newarray = [];

for (var i = 0, k = options.length; i < k; ++i){
    newarray[i] = options.eq(i).text(); 
}
console.log(newarray);

Probably good to know you can use for because it's similar to your first idea and you may need it when not including jQuery (of course the other jquery methods in my example wouldn't work in that case, but you get the idea).

http://jsfiddle.net/p7JWg/

Comments

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.