3

I want to store all the values of text inside an array in a loop, is it possbile? can someone give me a hint on how to do this?

 $('#wa li').each(function (i) {
 var text = $(this).text();
});
Ken White
126k15 gold badges237 silver badges476 bronze badges
asked Oct 20, 2017 at 2:01

3 Answers 3

5

Just use .map and .get – there's no need for intermediate variables or loops

const liTexts = 
 $ ('#wa li')
 .map ((idx,elem) => $(elem).text ())
 .get ()
 
console.log (liTexts)
// [ 'one', 'two', 'three' ]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="wa">
 <li>one</li>
 <li>two</li>
 <li>three</li>
</ul>

answered Oct 20, 2017 at 2:07
Sign up to request clarification or add additional context in comments.

8 Comments

Man, other people are the worst, am I right? (Kidding. And I agree that .map() is the way to go here.)
for a second I thought you had map's callback incorrect, before I checked jquery's documentation and realized their api is just backwards. Also, nice to meet you @nnnnnn
@aaaaaa - Likewise. I don't know, but I suspect it is backwards because you can use this to refer to the element, so then if you want the index too you can just define that one argument in your callback.
@aaaaaa - 20% this, 20% closures, 20% typos, 20% didn't read easily accessible documentation, 20% code this for me. (OK, I shouldn't have said 100%, there are good, non-duplicate questions too.)
i should change my name to vvvvvv
|
2
var myArr = []; // define the array
$('#wa li').each(function (i) {
 myArr.push($(this).text()); // push the value into the array
});
console.log(myArr); // ['hello', 'world', ...] use the array
answered Oct 20, 2017 at 2:02

Comments

2

You can use array.push() to the values to the array

var myArr = []; // define the array
$('#wa li').each(function (i) {
 myArr.push($(this).text()); 
});
answered Oct 20, 2017 at 2:03

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.