首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >getElementsby#方法在内h-t中的应用

getElementsby#方法在内h-t中的应用
EN

Stack Overflow用户
提问于 2017-04-26 06:24:14
回答 1查看 556关注 0票数 0

我试图在文本中检索通过内部h- to加载的各种元素的属性,但是我没有得到一个特定的元素。

这是我的代码:

代码语言:javascript
运行
复制
<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页面加载到高分子元素中的最佳方法吗?
  2. console.log的输出是如下所示的数组:

HTMLCollection 0: span.author 1: span.author 2: span.author长度:3 __proto__:HTMLCollection

这是正确的,有三个元素的类名“作者”。但是,当我对console.log(test[0])做同样的事情以获得第一个结果时,我得到"undefined"作为输出。如何才能得到第一个,更重要的是,span的值?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-26 14:58:36

  1. 是的,就我个人而言,我认为这是将HTML加载到聚合物元素中的最佳方法,除非您可以使用HTML导入作为正常的方法。
  2. 使用getElementsByClassName,您将获得一个HTML collection,并且无法直接访问这些元素的值。您可以使用不同的方法将其作为像Array.fromfor...of回路这样的数组来获得。另一种解决方案可能是使用简单的this.querySelectorAll()将它们作为一个数组。

Clarification 这里(StackOverflow答案) 这里(中篇).

代码语言:javascript
运行
复制
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));
    }
  });
});
代码语言:javascript
运行
复制
body {
  font-family: sans-serif;
}
代码语言:javascript
运行
复制
<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>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43626503

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档