Vims
Vims

Reputation: 179

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

I'm trying to retrieve properties on various elements within a text that is loaded through inner-h-t-m-l but I fail to get just one specific element.

Here is my code:

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

So I have two questions about this:

  1. Is this the best way to load an html page into a Polymer element?
  2. The output of the console.log is an array that looks like this:
HTMLCollection[0]
0: span.author
1: span.author
2: span.author
length: 3
__proto__: HTMLCollection

This is correct, there are 3 elements with class-name "author". But when I do the same thing with console.log(test[0]) in order to get just the first one, I get "undefined" as output. How do I get just the first one, and more importantly, the value of that span?

Upvotes: 0

Views: 589

Answers (1)

LasaleFamine
LasaleFamine

Reputation: 633

  1. Yes, personally I think this is the best way to load HTML into a Polymer element unless you can use HTML import as normal way to do this.

  2. With getElementsByClassName You are getting an HTML collection and you can't access directly the value of these elements. You can use different methods to get it as an array like Array.from or a for...of loop. Another solution could be getting them as an Array with the simple this.querySelectorAll().

Clarification here (StackOverflow 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>

Upvotes: 1

Related Questions