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();
});
3 Answers 3
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
Mulan
136k35 gold badges240 silver badges276 bronze badges
Sign up to request clarification or add additional context in comments.
8 Comments
nnnnnn
Man, other people are the worst, am I right? (Kidding. And I agree that
.map() is the way to go here.)aaaaaa
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 @nnnnnnnnnnnn
@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.nnnnnn
@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.)Mulan
i should change my name to vvvvvv
|
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
dhilt
21.1k8 gold badges79 silver badges96 bronze badges
Comments
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
Sajeetharan
223k65 gold badges370 silver badges410 bronze badges
Comments
lang-js