Search code examples
javascripthtmlonclickinnerhtml

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);

Solution

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