Skip to content

How can I add event listeners to a HTML element that is inside of a custom element

Gabriel Forti edited this page Jul 31, 2018 · 3 revisions

In order to do this, you will have to use a getter in the custom element class.

if we have an input field

<input class="password" required type="password" />

we can return the input as a getter in the class

function generateTemplate() {
        const template = document.createElement('template');
        template.innerHTML = `<input class="password" required type="password" />`;
        return template;
}

class PasswordReveal extends HTMLElement {

    constructor() {
      super();
      const shadowRoot = this.attachShadow({ mode: 'open' });
      shadowRoot.appendChild(generateTemplate().content.cloneNode(true));
      this.input = this.shadowRoot.querySelector('input')
    }

   get inputElement() {
      return this.input
   }
}

window.customElements.define('password-reveal', PasswordReveal);

We can then get the custom element DOM in JavaScript and be able to call that property

let passwordElem = document.querySelector('password-reveal')
passwordElem.addEventListener('click', (e)=>{
    console.log(passwordElem.inputElement.type)
})

console.log(passwordElem.inputElement.name)
passwordElem.inputElement.name = "login"
console.log(passwordElem.inputElement.name)

passwordElem.inputElement.addEventListener('input', function(){
    console.log(this.value)
})

The nice thing is that you cannot set a value to the inputElement property without a setter function in the class. The following would throw an error

passwordElem.inputElement = null
Clone this wiki locally