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>
querySelector() The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.
To check if an element does not exist in the DOM: Use the getElementById or querySelector methods to select the element. Check if the stored value is equal to null . If the value is equal to null , the element does not exist in the DOM.
The querySelector() method returns the first child element that matches a specified CSS selector(s) of an element. Note: The querySelector() method only returns the first element that matches the specified selectors. To return all the matches, use the querySelectorAll() method instead.
getElementById matches the id attributes to find DOM nodes, while querySelector searches by selectors. So for an invalid selector e.g <div id="1"></div> , getElementById('1') would work while querySelector('#1') would fail, unless you tell it to match the id attribute (e.g querySelector('[id="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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With