问题
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