Becky Becky - 7 months ago 28
Javascript Question

Get text from an array

I got an array wich 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...
});

Answer

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>

Comments