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

231
Vistas
How to use onClick function inside innerHTML

This is my JS file, it is one of reusable HTML components since I'm not using any framework. Before this I'm using ReactJS, since for some reason, I required not to use any framework for frontend.

My question is I want to make onClick function for the button. I thought it is the same thing as using JSX in ReactJS but it doesn't work. I want to add the <script> tag in the innerHTML but I don't think it is relevant because this is already a javascript file.

class Header extends HTMLElement {
    connectedCallback() {
        this.innerHTML =
           `
             <button onclick="">Try it</button>
           `
    }
}

customElements.define('main-header', Header);
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

<button onclick="fn()">Try it</button>
Or you can write code in the quotes directly:
onclick="console.log('click')"

about 4 years ago · Juan Pablo Isaza Denunciar

0

HolaPz is correct, but to more clearly demonstrate-

function buttonClicked()
{
  console.log("You son of a gun, you did it");
}

class Header extends HTMLElement {
    connectedCallback() {
        this.innerHTML =
           `
             <button onclick="buttonClicked()">Try it</button>
           `
    }
}

customElements.define('main-header', Header);

NOTE: when buttonClicked is called, the "this" context will be set to the Window object and only top-level functions will be available. Depending on how you want to code going forward, it might make sense to use this.querySelector inside connected callback to get a reference to the button and then manually add a bound function or event listener (via addEventListener) to it.

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