document.querySelector() returns null

偶尔善良 提交于 2019-12-06 18:34:51

问题


I'm creating a polymer element. I've made the template and am now working on the script. For some reason document.querySelector is returning null for both class and id selectors. Not sure if this doesn't work with polymer (no reason it shouldn't) or I haven't imported something or what else is wrong.

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>

回答1:


<event-card-description id="description"> is in your element's shadow dom. document.querySelector("#description") is looking for a node with id#description in the main document. It's expected that the node isn't found because the shadow dom boundary hides it. Try:

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

However, Polymer has an awesome feature where static elements that have ids are mapped to this.$.<id>. You can use this.$.description to get at that element.




回答2:


for multiple value in attributes use ~ sign, e.g.

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

or if you want to use this only for element polymer-element use:

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


来源:https://stackoverflow.com/questions/25100883/document-queryselector-returns-null

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