Emil Jamel Mahmuda
Emil Jamel Mahmuda

Reputation: 21

How can I select elements in shadow dom through the parent element based on the click event on addEventListener?

I have a web component, like this:

File: download-bar.js (web component)

class DownloadBar extends HTMLElement {

    constructor() {
        super();
        this.shadowDOM = this.attachShadow({mode: 'open'});        
    }

    connectedCallback() {
        this.render();
    }

    render() {
        this.shadowDOM.innerHTML = `
            <div class="favicon">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="black" width="18px" height="18px"><path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"></path><path d="M0 0h24v24H0z" fill="none"></path></svg>
                <span>Download File</span>
            </div>
            <div class="dropdown">
                <a href="" id="xlsx">XLSX</a>
                <a href="" id="pdf">PDF</a>
                <a href="" id="jpeg">JPEG</a>
            </div>
        `;
    }
}

customElements.define('download-bar', DownloadBar);

and I do a selection of elements on the parent shadow element DOM and listen to the click event, like this:

File: download-bar.js

import '../component/download-bar.js';

const downloadElement = document.querySelector('download-bar');

downloadElement.addEventListener('click', (e) => {

    // I would like this:
    if (e.target.classList.contains('favicon')) {
        console.log('True')
    }
})

how can I get child elements from custom elements using shadow dom, if an event from "(e)" that is obtained has a certain class or id, for example class = "favicon"?

Upvotes: 0

Views: 1632

Answers (1)

You need to use event.composedPath()

If you use Custom Events be sure to set the composed:true option so your event breaks out of shadowDom

BTW

You can replace all this:

    constructor() {
        super();
        this.shadowDOM = this.attachShadow({mode: 'open'});        
    }

    connectedCallback() {
        this.render();
    }

    render() {
        this.shadowDOM.innerHTML = ...

with:

    connectedCallback() {
        this.attachShadow({mode: 'open'}).innerHTML = ...
    }

You aren't doing anything special in the constructor; so don't define it and let the element run the constructor from HTMLElement.

attachShadow() both sets and returns this.shadowRoot

Only when you move/append/drag around Custom Elements in the DOM will the connectedCallback run again, and you might want to split creating shadowDOM to its own constructor


Also see: https://pm.dartus.fr/blog/a-complete-guide-on-shadow-dom-and-event-propagation/

Upvotes: 1

Related Questions