Becky
Becky

Reputation: 5585

Get text from an array

I have an array which has button elements in a certain order.

var arr = [ $('.buttons')[0], $('.buttons')[2], $('.buttons')[1], $('.buttons')[4] ];

How do I get the text of each button? Below is what I tried.

$.each(arr, function (index, value) {
      var butText = value.text();
      //do something...
});

Upvotes: 0

Views: 101

Answers (3)

Jacob See
Jacob See

Reputation: 775

If you want to extract the text of those elements to a new array without $.each() looping, you can use use map().

var arr = [ $('.buttons')[0], $('.buttons')[2], $('.buttons')[1], $('.buttons')[4] ];
var texts = arr.map(function(a) {return a.text();});

which will return an array equivalent to

[ $('.buttons')[0].text(), $('.buttons')[2].text(), $('.buttons')[1].text(), $('.buttons')[4].text() ]

Upvotes: 1

Ibrahim Khan
Ibrahim Khan

Reputation: 20740

You need to use jQuery object $(this) to get button text.

var arr = [$('.buttons')[0], $('.buttons')[2], $('.buttons')[1], $('.buttons')[4]];

$.each(arr, function () {
    var butText = $(this).text();
    console.log(butText)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="buttons">button 0</button>
<button class="buttons">button 1</button>
<button class="buttons">button 2</button>
<button class="buttons">button 3</button>
<button class="buttons">button 4</button>

Upvotes: 1

Rion Williams
Rion Williams

Reputation: 76547

If you want to retrieve each of them in the specified order, you could just consider looping through them, using $(this) to refer to each element in the iteration :

// Iterate through each element
$.each(arr, function(){
      // Get the text (this will refer to each of your elements)
      var buttonText = $(this).text();
      // Do something here
});

Complete Example

var arr = [ $('.buttons')[0], $('.buttons')[2], $('.buttons')[1], $('.buttons')[4] ];
$.each(arr,function(){
    alert($(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class='buttons'>A</button>
<button class='buttons'>B</button>
<button class='buttons'>C</button>
<button class='buttons'>D</button>
<button class='buttons'>E</button>

Upvotes: 3

Related Questions