简体   繁体   中英

Set content of custom HTML element

I implemented a modal as a custom HTML tag.

class ModalDialog extends HTMLElement {
    constructor() {
        super();

        this.shadow = this.attachShadow({
            mode: 'open'
        });

        this.modal = document.createElement('div');
        this.modal.className = 'modal';

        this.modalWrapper = document.createElement('div');
        this.modalWrapper.className = 'modal-wrapper';

        this.modalHeader = document.createElement('div');
        this.modalHeader.className = 'modal-header';
        this.modalHeader.innerHTML = 'Oops, nothing found!';
        ...
    }

Also, I implemented another class which inherits from HTMLElement. Let's call it A. Said class is trying to create a ModalDialog and should add it to the DOM so it will be displayed.

Now, my question is: How can I set the text of the modalHeader from class A? I tried to set an attribute and read it in the ModalDialog class but at that time, the attribute is undefined.

class A extends HTMLElement {
    ...
    this.modal.setAttribute('headerText', 'Blablabla');
    ...
}

Is there any good way to solve this?

Your class A should be able to just access the inner elements and set either their innerHTML or textContent like this:

class A extends HTMLElement {
  ...
  this.modal.innerHTML = 'Blablabla';
  ...
}

Also, make sure you are placing this.modal into the shadowRoot :

this.shadowRoot.appendChild(this.modal);

On other thing to be aware of is that you do not need to save off the results of this.attachShadow :

 this.shadow = this.attachShadow({mode: 'open'});

Since that is already available as this.shadowRoot .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM