-1

I'm writing a simple app in vanilla JS. I have an array of strings, and I want to map thru the array and assign the values to innerHTML to the buttons. Can I do it with .map()? As of right now, the most I can get is the last thing assigned to the button's innerHTML ('next >')

Here's my code

var buttons = document.getElementsByTagName("button");
const a = ["click for more", "see more", "details page", "next >"];

a.map((i) => {
  buttons.innerHTML = i;
});
<div>
  <button>Submit</button>
  <button>Submit</button>
  <button>Submit</button>
  <button>Submit</button>
</div>
<script src="index.js"></script>

1
  • What do you think the s in document.getElementsByTagName signals? Commented Dec 8, 2022 at 14:38

2 Answers 2

3

You're so close to the solution. You just need to access the array items with index you get from Array.forEach()

Note that Array.map() is replaced with Array.forEach() since you don't use the return value of the map() function which creates a new array. (Thanks to @Ivar)

var buttons = document.getElementsByTagName("button");
const a = ["click for more", "see more", "details page", "next >"];

a.forEach((text, index) => {
  buttons[index].innerHTML = text;
});
<body>
    <div>
      <button>Submit</button>
      <button>Submit</button>
      <button>Submit</button>
      <button>Submit</button>
    </div>
    <script src="index.js"></script>
  </body>

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

Comments

1

You missed to index the button

If you use querySelectorAll on the buttons, you get a NodeList.forEach, that makes more sense than the one using the Array.forEach

var buttons = document.querySelectorAll("button");
const a = ["click for more", "see more", "details page", "next >"];

buttons.forEach((but, i) => {
  but.innerHTML = a[i];
});
<body>
  <div>
    <button>Submit</button>
    <button>Submit</button>
    <button>Submit</button>
    <button>Submit</button>
  </div>
  <script src="index.js"></script>
</body>

2 Comments

For completion - and it's not worth providing yet another answer - it's worth noting that given the NodeList of elements and the Array of Strings, there's two possibilities: demo, one with NodeList.prototype.forEach(), and the other with Array.prototype.forEach().
OP IS looping over the result from the getElements No. They are looping over an array of strings. It's exactly the thing marked as a dupe.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.