Reading data-attribute from element inside iron-li

2019-07-29 11:17发布

I create a list of divs using an iron-list like this:

<iron-list items="[[chats]]" as="item" style="height:500px;">
    <template>
        <div class="item title" data-recipient$="[[item.recipient]]">
            <iron-icon class="big" src="../icons/games.svg"></iron-icon>
        </div>
    </template>
</iron-list>

I have a Polymer method which is called later-on and loops the div.title.

I can then manage to set their color, but I can not manage to read out the data-attribute:

var elems = document.querySelectorAll(".title");
[].forEach.call(elems, function(el) {
    el.style.color = "red"; // works
    console.log(el.getAttribute("data-recipient")); // prints out null
});

Why is that?

1条回答
我想做一个坏孩纸
2楼-- · 2019-07-29 11:49

If you're inside a Polymer method, avoid using document.querySelector() because it queries the entire document instead of only your element's local DOM, and this function would not be able to query the element's shadow DOM. You should use this.$$('.title') instead.

However, I cannot reproduce the symptom you're seeing in this Codepen (i.e., el.dataset.recipient and el.getAttribute('data-recipient') both return the expected value).

查看更多
登录 后发表回答