在 innerhtml 上使用 getElementbyid# 方法的聚合物

Polymer using getElementsby# method on inner-h-t-m-l

我正在尝试检索通过 inner-h-t-m-l 加载的文本中各种元素的属性,但我无法只获取一个特定元素。

这是我的代码:

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

所以我有两个问题:

  1. 这是将 html 页面加载到 Polymer 元素中的最佳方式吗?
  2. console.log 的输出是一个如下所示的数组:
HTMLCollection[0]
0: span.author
1: span.author
2: span.author
length: 3
__proto__: HTMLCollection

这是正确的,有 3 个元素具有 class-name "author"。但是当我用 console.log(test[0]) 做同样的事情以获得第一个时,我得到 "undefined" 作为输出。我怎样才能得到第一个,更重要的是,那个 span?

的值
  1. 是的,我个人认为这是将 HTML 加载到 Polymer 元素中的最佳方法,除非您可以使用 HTML import 作为常规方法来执行此操作。

  2. getElementsByClassName 你得到一个 HTML collection 并且你不能直接访问这些元素的值。 您可以使用不同的方法将其获取为数组,如 Array.from or a for...of loop。 另一种解决方案是使用简单的 this.querySelectorAll().

  3. 将它们作为数组获取

澄清here (Whosebug answer) and here (Medium article).

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>