Search code examples
javascripthtmlinnerhtml

InnerHTML not displaying the content in string


I am trying to display two buttons with .innerHTML but it doesn't display the content put in the string. The console is not showing any error and I've checked for typos but I haven't found anything.

Here's my HTML :

<div class="buttons">
   <div class="buttons_inner" id="buttonShiny"></div>
</div>

And here's my JS :

const shiny = document.getElementById('buttonShiny');

const displayButtonShiny = (pokemon) => {
  const shinyHTMLString = `
    <button class="buttons_shiny" onclick="document.getElementById('pokemonSprite').src='https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/${pokemon.id}.png'">Shiny</button>
    <button class="buttons_normal" onclick="document.getElementById('pokemonSprite').src='https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${pokemon.id}.png'">Normal</button>
    `;
    shiny.innerHTML = shinyHTMLString;
};

The content in the shinyHTMLString should be displayed in the #buttonShiny div but it doesn't work

The script tag to call the JS file is right before the closing body tag


Solution

  • Yes you declare the function but never use it. Add only displayButtonShiny("x") to your js code.

    const shiny = document.getElementById('buttonShiny');
    
    const displayButtonShiny = (pokemon) => {
      const shinyHTMLString = `
        <button class="buttons_shiny" onclick="document.getElementById('pokemonSprite').src='https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/${pokemon.id}.png'">Shiny</button>
        <button class="buttons_normal" onclick="document.getElementById('pokemonSprite').src='https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${pokemon.id}.png'">Normal</button>
        `;
        shiny.innerHTML = shinyHTMLString;
    };
    
    displayButtonShiny("x"); // x = your pokemon
    <div class="buttons">
       <div class="buttons_inner" id="buttonShiny">btn1</div>
    </div>