Skip to content Skip to sidebar Skip to footer

Passing Parameter/input Data To Custom Elements In Javascript

I'm trying to implement the same code of this using JavaScript, so wrote the below code as btn.js file: // Create a new object based of the HTMLElement prototype var SaveBtn = Obje

Solution 1:

The shadow DOM root is only accessible within the function-scope it is defined. You either need to assign the shadow DOM root object to an outer-scope variable, or you need to expose an in-scope function that manipulates the shadow DOM. Since you want to manipulate the shadow DOM for multiple elements, a setter function on each instance is the best option.

You can expose the shadow DOM entirely:

SaveBtn.createdCallback = function() {
    var shadow = this.createShadowRoot();
    this.myShadow = shadow;
    //...
}

...

el.myShadow.textContent = "click me";

However, since a major feature of the shadow DOM is being able to hide DOM components from manipulation by other scripts, you may instead wish to have a setter function that (for example) validates input and performs the manipulation internally:

SaveBtn.createdCallback = function() {
    var shadow = this.createShadowRoot();

    this.setShadowText = function(text) {
        shadow.textContent = text;
    }
    //...
}

...

el.setShadowText("click me");

Post a Comment for "Passing Parameter/input Data To Custom Elements In Javascript"