0

I would like to set content to each button.

I have array and would like to set A,B,C,D.

But now,in my work below, the result is a little different.

Are there any way to achieve it ?

Thanks

arr=["A","B","C","D"]

$(".button").text(arr);
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>

<div>
  <button class="button"></button>
  <button class="button"></button>
  <button class="button"></button>
  <button class="button"></button>
</div>

1
  • You mean the four buttons get the four values from the array? Button 1 text 'A', button 2 'B' ...?? Commented May 3, 2020 at 10:36

2 Answers 2

3

Since .button will give a all the elements with same class , you need to iterate it. Use each to iterate the object. each takes first argument as the element and second one as index. Use this index to retrieve the value from array. Then use text to set the content of the button

let arr = ["A", "B", "C", "D"]

$(".button").each(function(i, v) {
  $(v).text(arr[i])

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <button class="button"></button>
  <button class="button"></button>
  <button class="button"></button>
  <button class="button"></button>
</div>

Sign up to request clarification or add additional context in comments.

Comments

0

Even though the answer of brk is completly valid I'd personally create a unique button for each element inside your array. This way you dont run into problems if there is not enough buttons in your html for each element or vice versa.

arr = ["A", "B", "C", "D"]


arr.forEach(element => createButton(element));

function createButton(text) {
  var newButton = document.createElement("button");
  newButton.setAttribute('class', 'button');
  newButton.innerHTML = text;
  document.body.appendChild(newButton);
}

2 Comments

Or, as OP is using jquery already: arr.forEach(txt => $("body").append(`<button class='button'>${txt}`));
Very nice one-liner! Thanks! @freedomn-m

Your Answer

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.