Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

223
Visualizações
Javascript Generated HTML Buttons with onClick Custom Function

I have an HTML page that has javascript, I'd like the javascript to generate HTML buttons like this:

<button class="btnFormat" onclick="var link = document.createElement('a');
        link.href = '#xxxxx';
        link.click(); window.location.reload() "> AYOU1 </button>
<button class="btnFormat" onclick="var link = document.createElement('a');
        link.href = '#xxxxx';
        link.click(); window.location.reload() "> AYOU1 </button>
<button class="btnFormat" onclick="var link = document.createElement('a');
        link.href = '#xxxxx';
        link.click(); window.location.reload() "> AYOU1 </button>

I can't seem to figure out how to get the javascript to add the class or onClick 'strings'. My code runs without errors but looking at the output it is just:

<button>AYOU1</button>
<button>AYOU2</button>
<button>AYOU3</button>

This is the code that I have been working on (it doesn't have the class=, as I can't figure out the onClick= part...):

  <html>

    <body>

<script>
    var items = [
      {hex: "OBFPUOX6T",            alpha: "AYOU1"          },
      {hex: "LC7THLODH",            alpha: "AYOU2"          },
      {hex: "RNPODALAJ",            alpha: "AYOU3"          },
      {hex: "2FSCQ4LGK",            alpha: "AYOU4"          },
    ]

    var i = 0;
    const parentElement = document.querySelector('body'); // DOM location when buttons will be added

    items.forEach(function(item) {
      const pButton = document.createElement("button");
      pButton.innerText = item.alpha;
      pButton.onClick = function() {
        var link = document.createElement('a');
        link.href = '#' + item.hex;
        window.location.reload();
      };
      i++;
      console.log(pButton, i)
      parentElement.appendChild(pButton); // to add new element to DOM
    })

</script>
    </body>

    </html>

I would appreciate any help! Thank you in advance!

I added the full source code here: https://jsfiddle.net/kilimar/7eL15azm/

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If your output doesn't show any classes, it's because all of the events are handled in the background, it is also probably a good practice to do it that way.

Though, your script have some errors and can be simplified:

  1. pButton.onclick is lowercase (not pButton.onClick)

    pButton.onclick = function() { // [...]
    
  2. Then there's a very useful property: location.hash (also window is not necessary)

    location.hash = '#' + item.hex;
    location.reload();
    
  3. (Bonus!) there's a shortcut for document.querySelector('body')

    const parentElement = document.body
    

Anyways, here's the whole code:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <script>
      var items = [
        {hex: "OBFPUOX6T", alpha: "AYOU1"},
        {hex: "LC7THLODH", alpha: "AYOU2"},
        {hex: "RNPODALAJ", alpha: "AYOU3"},
        {hex: "2FSCQ4LGK", alpha: "AYOU4"},
      ]

      var i = 0;
      const parentElement = document.body; // DOM location when buttons will be added

      items.forEach(function(item) {
        const pButton = document.createElement("button");
        pButton.innerText = item.alpha;
        pButton.onclick = function() {
          location.hash = '#' + item.hex;
          location.reload();
        };
        i++;
        console.log(pButton, i)
        parentElement.appendChild(pButton); // to add new element to DOM
      })
    </script>
  </body>
</html>

I hope this helped !

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda