How to set inner text of tag in web component

1.6k Views Asked by At

I am making use of the x-tags. Here is the code that I am working on. I need to set the content of these div boxes with value of custom elements attribute value. Is it possible to do this? I tried setting it but I got error "undefined is not a function".

var template = xtag.createFragment(function(){/*
  <div>
    <div id="box1"></div>
    <div id="box2"></div>
    <div id="box3"></div>
  </div>
*/});

xtag.register('x-navbar', {
  lifecycle: {
    created: function() {
      this.appendChild(template.cloneNode(true));
      this.getElementById("#box1").innerHTML = this.productName;
    },
  accessors: {
    productName: {
      attribute: {},
      get: function(){
        return this.getAttribute('productName') || "";
      },
      set: function(value){
        this.xtag.data.header.setAttribute('productName',value);
      }
    }
  }
});

<x-navbar productName="Box 1">hii</x-navbar>
2

There are 2 best solutions below

1
Bahtiyar Özdere On

You can write the attribute backing accessors like this. You dont need to try setup attributes manually. Since it will update itself from to returning value from get function.

accessors: {
            productName: {
                attribute: {},
                get: function () { return this._productName; },
                set: function (value) { 
                     this._productName = value;
                     // MANUPLATE YOUR HTML IN HERE
                     this.getElementById("#box1").innerHTML = this.productName;
                }
            },
}
0
jpec On

You can simplify this even further, because you are not changing the productName in the setter:

xtag.register('x-navbar', {
  content: function() {/*
  <div>
    <div id="box1"></div>
    <div id="box2"></div>
    <div id="box3"></div>
  </div>
*/},
  accessors: {
    productName: {
      attribute: {},
      set: function (name) {
        this.querySelector('#box1').textContent = name;
      }
    }
  }
});

Which you would use like this:

<x-navbar product-name="Testing 123">hii</x-navbar>

Note that the attribute name must be the dasherized version of productName, product-name. This would be rendered as:

hii
Testing 123

The template <div> structure is added after the element's content, hii.