我试图在文本中检索通过内部h- to加载的各种元素的属性,但是我没有得到一个特定的元素。
这是我的代码:
<template>
<iron-ajax
auto
url="[[some/path/url.html]]"
handle-as="text"
last-response="{{inputText}}"></iron-ajax>
<div class="textcontent" inner-h-t-m-l="{{inputText}}"></div>
</template>
<script>
Polymer({
is: 'text-page',
ready: function() {
var test = document.getElementsByClassName("author");
console.log(test);
}
});
</script>
我有两个问题要问:
HTMLCollection 0: span.author 1: span.author 2: span.author长度:3 __proto__:HTMLCollection
这是正确的,有三个元素的类名“作者”。但是,当我对console.log(test[0])
做同样的事情以获得第一个结果时,我得到"undefined"
作为输出。如何才能得到第一个,更重要的是,span
的值?
发布于 2017-04-26 14:58:36
getElementsByClassName
,您将获得一个HTML collection
,并且无法直接访问这些元素的值。您可以使用不同的方法将其作为像Array.from或for...of回路这样的数组来获得。另一种解决方案可能是使用简单的this.querySelectorAll()
将它们作为一个数组。Clarification 这里(StackOverflow答案) 和 这里(中篇).
const html = `<span class="author">test</span><span class="author">another</span>`
addEventListener('WebComponentsReady', function() {
Polymer({
is: 'x-example',
properties: {
html: {
type: String,
value: html
}
},
ready: function() {
// 1° solution
const test = this.getElementsByClassName('author');
const first = Array.from(test)[0];
console.log('First element innerText --->', first.innerText);
// Or you can simply loop on the array
Array.from(test).forEach(item => console.log(item.innerText));
// 2° solution
const test2 = this.querySelectorAll('.author');
test2.forEach(item => console.log(item.innerText));
}
});
});
body {
font-family: sans-serif;
}
<base href="https://polygit.org/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link href="polymer/polymer.html" rel="import">
<dom-module id="x-example">
<template>
<style>
:host {
display: block;
}
</style>
<h1>polyfiddle</h1>
<div inner-H-T-M-L="[[html]]">
</div>
</template>
</dom-module>
<x-example></x-example>
https://stackoverflow.com/questions/43626503
复制相似问题