document.querySelector() returns null

user3903150 picture user3903150 · Aug 3, 2014 · Viewed 18.7k times · Source

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>

Answer

ebidel picture ebidel · Aug 3, 2014

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