javascripthtmlpolymergetelementbyidpolymer-2.x

Cannot get element by id in Polymer 2


I have a problem with getting HTML element inside dom-repeat in a function.

At first I had this code and it worked OK.

HTML:

<div class="card">
  <app-toolbar>
    <paper-button on-click="downloadTable">[[localize('Download')]]</paper-button>
  </app-toolbar>
  <table id="table" noshadow>
  <!--Table content here-->
  </table>
</div>

JS:

downloadTable() {
    this.tableToExcel(this.$.table, 'table.xls');
}

But then I went from a single table to multiple tables which are iterated with dom-repeat.

HTML:

<template id="tablesRoot" is="dom-repeat" items="[[tables]]" as="table">
    <div class="card">
      <app-toolbar>
        <paper-button on-click="downloadTable">[[localize('Download')]]</paper-button>
      </app-toolbar>
      <table id={{table.elId}} noshadow>
      <!--elId is a string: table0, table1, table2, ... Table content here-->
      </table>
    </div>
</template>

JS:

downloadTable() {
    this.tableToExcel(this.$.table0, 'table.xls');
    //Trying to get the first table. Also tried without success:
    //this.$.tablesRoot.table0
    //this.$.tablesRoot.$.table0
}

In the element inspector is seems, ids are added correctly both for table and dom-repeat. But still cannot access any table. How I need to do this?


Solution

  • It seems, you cannot address dynamically created elements like this. Instead you have to use:

    Polymer.dom(this.root).querySelector('#table0')