document.querySelector() returns null

document.querySelector() returns null

本文关键字:returns null querySelector document      更新时间:2023-09-26

我正在创建一个聚合物元素。我已经制作了模板,现在正在编写脚本。由于某种原因,文件。querySelector对于类和id选择器都返回null。不确定这是否与聚合物不起作用(没有理由不应该),或者我没有进口的东西或其他什么是错误的。

event-card.html

<link rel="import" href="../components/polymer/polymer.html">
<link rel="import" href="event-card-description.html">
<polymer-element name="event-card" attributes="header image description">
  <template>
    <style>
      .card-header {
        display: block;
        position: static;
        font-size: 1.2rem;
        font-weight: 300;
        width: 300px;
        height: 300px;
        border-radius: 50%;
        -webkit-border-radius: 50%;
        -moz-border-radius: 50%;
        overflow: hidden;
      }
      event-card-description {
        margin: 0;
        position: relative;
        top: 225px;
      }
    </style>
    <div 
      style="background: url(../images/{{image}}.jpg) no-repeat; background-size: cover" 
      class="card-header" layout horizontal center
      on-mouseover='{{onHovered}}' 
      on-mouseout='{{onUnhovered}}'>
      <event-card-description
        id="description"
        header={{header}} 
        description={{description}}>
      </event-card-description>
    </div>
  </template>
  <script>
    Polymer('event-card', {
      onHovered: function() {
        var elem = document.querySelector("#description");
        console.log(elem);
      }
    });
  </script>
</polymer-element>

<event-card-description id="description">在元素的阴影域中。document.querySelector("#description")主文档中寻找具有id#description的节点。因为阴影dom边界隐藏了节点,所以没有找到该节点。试一试:

this.shadowRoot.querySelector("#description");

然而,聚合物有一个令人敬畏的功能,其中具有id的静态元素映射到this.$.<id>。您可以使用this.$.description来获取该元素

对于属性中的多个值使用~符号,例如

var elem = document.querySelector("[attributes~=description]");

或者如果你想只对元素polymer-element使用:

var elem = document.querySelector("polymer-element[attributes~=description]");