Skip to content Skip to sidebar Skip to footer

How To Create An Element In Javascript And Pass Parameters To It?

In the new v1 web components spec, you can create a new element by saying like class gg extends HTMLElement { constructor(a) { super(); } } customElements.define('

Solution 1:

You can use a function to create a class expression where default parameters are used to set constructor

const gcreate = (...props) => {
  const gg = class extends HTMLElement {
    constructor(a = props) {
      console.log(a);
      a.find(prop => 
        typeof prop === "object"
        && !Array.isArray(prop))
        ["def"](789)
      super();
    }
  }
  customElements.define('gg-gg', gg);
  return document.createElement("gg-gg");
}

let g = gcreate(
        // pass parameters
        "abc"
        , 123
        , [4,5,6]
        , {def:(prop) => console.log(prop)}
        , null, void 0
        );

Solution 2:

You can pass and options object at second parameter to document.createElement() where property is set to "is", within contructor use setTimeout() call .getAttribute() on variable identifier referencing super() to get value of "is" property

class gg extends HTMLElement {
    constructor(a) {
        const curr = super();
        setTimeout((el) => {
          console.log(JSON.parse(el.getAttribute("is")))
        }, 0, curr)
    } 
}

customElements.define('gg-gg', gg);

const g = document.createElement("gg-gg", {"is":JSON.stringify({"abc":123})});

Solution 3:

Here's another way you can load in arguments into your constructor. It works by loading in a temp payload.

// Args
var args;

// Create Element
var createElem = function (element, arguments) {
  typeof arguments === 'undefined' ? args = {} : args = arguments;
  return document.createElement('gg-gg');
}

// Define Custom Component
customElements.define('gg-gg', class extends HTMLElement {
  constructor() {
    super();
    console.log(args);
  }
});

// Arguments
createElem('gg-gg', {
  width: 500,
  height: 500,
});

// No arguments
createElem('gg-gg');

Post a Comment for "How To Create An Element In Javascript And Pass Parameters To It?"