Behseini
Behseini

Reputation: 6328

Issue on Using jQuery each() to Load Elements of Array in DOM Elements

Can you please take a look at this code and let me know how I can use the .each() to load each elements of array to the buttons?

var arr=["Left","Middle", "Right" ];
 $("button").each(function(){
        $(this).html(arr);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn-group" role="group" aria-label="...">
  <button type="button" class="btn btn-default">x</button>
  <button type="button" class="btn btn-default">x</button>
  <button type="button" class="btn btn-default">x</button>
</div>

Upvotes: 0

Views: 47

Answers (2)

kosmos
kosmos

Reputation: 4288

If the array order is the desired, use the index parameter provided by the .each() method:

var arr = ["Left","Middle", "Right"];
$("button").each(function(i){
    $(this).html(arr[i]);
});

Upvotes: 1

DinoMyte
DinoMyte

Reputation: 8868

You certainly can. You use the index of each button in the DOM and use it to iterate through the array

var arr=["Left","Middle", "Right" ];
 $("button").each(function(i){
        $(this).html(arr[i]);
    });

http://jsfiddle.net/d14z32fq/

Upvotes: 1

Related Questions