Reading data-attribute from element inside iron-list

时光总嘲笑我的痴心妄想 提交于 2019-12-24 10:36:50

问题


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:


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).



来源:https://stackoverflow.com/questions/42328783/reading-data-attribute-from-element-inside-iron-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!