How can I make a dynamic button array which changes the src of an image according to a dynamic object array?

I am a beginner with Javascript and I am still experimenting with how things work. My knowledge is very limited. Excuse me if I phrase something falsely.

I am trying to make a dynamic system in which the length of an array prints out an amount buttons accordingly. My issue lies on the buttons’ function. I want each button to change the src of an image according to the array I made once clicked.

eg:

  • Def button -> changes the src of img to a singular variable (default url)
  • Array button #1 -> changes the src of the img to array variable #1
  • Array button #2 -> changes the src of the img to array variable #2
  • etc…

Here’s how my code looks thus far:

HTML:

<img src="#" id="diplayimg">
<div class="charskins">
  <p><span id="data_skins"></span></p>
</div>

JS:


//this is the default src the image is going to have
let diplayimgPath = 'imagedef.png';

//name = text displayed on the new button and url = the new src of the image
let skinsData = {
  skins: [
    { name: 'Skin 0', url: 'image1.png' },
    { name: 'Skin 1', url: 'image2.png' }
    //Note that there can be added as many arrays of objects as I like here
  ]
}

let defaultskin = '<button onclick="changeSkinDef()">Default</button>';

function changeSkinDef() {
  document.getElementById("diplayimg").src = diplayimgPath;
}

if (document.getElementById("data_skins")) {
  function changeSkinNew() {
    skinspathFinal = '';
    for (let i = 0; i < skinsData.skins.length; i++) {
      let skinimg = document.getElementById("diplayimg");
      skinimg.setAttribute("src", skinsData.skins[i].url);
      skinspathFinal += skinimg;
    }
    return skinspathFinal;
  }

  function printSkins(){
    let skinsFinal = '';
    for (let i = 0; i < skinsData.skins.length; i++) {
      skinsFinal += '<button onclick="changeSkinNew()">' + skinsData.skins[i].name + '</button>';
    }
    return defaultskin + skinsFinal;
  }
  document.getElementById("data_skins").innerHTML= printSkins();
}

The buttons are printed normally with their given “names”. The new urls of the images are read correctly too, however the new buttons change the src of the image only to one specific url I have set in the objects’ array.

eg:

  • Array button #1 -> changes src to variable #1
  • Array button #2 -> changes src to variable #1, again

I reckon the changeskinNew() function is causing the problem, since all new buttons activate the same function once clicked, but I have no clue how I can make the functions dynamic as well.

Any suggestions on how I can make this work?

ps: I have tried using the forEach and createElement method to manually create the buttons, but it did not seem to work either.