-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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Mateusz Szumilo
  • 109
  • 2
  • 7

2 Answers2

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>
Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 2
    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](https://jsfiddle.net/davidThomas/3cm7ows9/), one with [`NodeList.prototype.forEach()`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach), and the other with [`Array.prototype.forEach()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach). – David Thomas Dec 08 '22 at 14:24
  • *OP IS looping over the result from the getElements* **No.** They are looping over an array of `string`s. It's exactly the thing marked as a dupe. – connexo Dec 09 '22 at 08:38