javascript document.querySelector() 返回 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25100883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
document.querySelector() returns null
提问by user3903150
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.
我正在创建一个聚合物元素。我已经制作了模板,现在正在编写脚本。出于某种原因,document.querySelector 为 class 和 id 选择器都返回 null。不确定这是否不适用于聚合物(没有理由不应该),或者我没有导入某些东西或还有什么问题。
event-card.html
事件卡.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>
回答by ebidel
<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:
<event-card-description id="description">
在你元素的 shadow dom 中。document.querySelector("#description")
正在寻找一个节点与id#description
中主文档。预计未找到该节点,因为 shadow dom 边界将其隐藏。尝试:
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.
但是,Polymer 有一个很棒的功能,其中具有 id 的静态元素映射到this.$.<id>
. 您可以使用this.$.description
来获取该元素。
回答by 31113
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:
或者如果您只想将其用于元素polymer-element
使用:
var elem = document.querySelector("polymer-element[attributes~=description]");