polymerpolymer-1.0dom-repeat

Access dom-repeat element's CSS class on tap


My dom repeat displays a list of icons which I can bookmark or unbookmark ,which generating dom-repeat I call a function to find if this icon is bookmarked or not,that will return CSS class

 .book-marked {
    color: red;
  }

  .not-book-marked {
    color: green;
  }

  <template is="dom-repeat" items="{{membersList}}">    
        <iron-icon icon="bookmark" class$="[[_computeBookMark(item.userId)]]" on-tap="_toogleBookMark"></iron-icon>     
  </template>

Once I get all my list of icon now if user click that icon I need to toogle css class.so I wrote on-tap function

  _toogleBookMark:function(e) {
    var userData = e.model.item;  //gets entire data object of that element
    var index = e.model.index;    //gets index of that element
  },

I can't use ID since its dom-repeat ,Is there any other ways so that I can change CSS of that dom-repeat element in _toogleBookMark() function on clicking? or is it possible to change CSS with index??or using "e" reference in _toogleBookMark(e) function !!


Solution

  • Not sure if I understood correctly - you want to access the element you've tapped?

    Just use the event.target property then. It will return the element on which the event happened, in this case, the icon you have tapped.

    _toogleBookMark = function(e) {
    e.target.classList.toggle("not-book-marked");
    

    }

    Check this example.

    Mind you:

    1) When using Shady DOM, assuming our element is a custom element, target can be a component from the element's template, not the element itself. To prevent that, use Polymer.dom(e).localTarget (read more here).

    2) When using a custom element with light DOM children, the above may not be enough, your (local)target will be a light DOM child, not the element you wished for. In that case, use Element.closest(selector) to (optionally) go up the DOM to the element you want. Read more about the method here.