Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

221
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda