Merc
Merc

Reputation: 17057

Custom elements without shadow DOM: best way to get an element

Using Polymer, I learned to understand well the difference between light DOM (whatever is in the element) and local DOM (the "hidden" side of the story).

<iron-form> (which is used like <form is="iron-form"></form>) is a little different as it doesn't have local DOM.

Now I have a custom-made widget (which is actually available in GitHub) where you go:

    <hot-form-validator success-message="Record saved!">
      <form is="iron-form" id="form" method="post" action="/stores/polymer">
        <paper-input required id="name" name="name" label="Your name"></paper-input>
        <paper-input required id="surname" name="surname" label="Your surname"></paper-input>
        <paper-button type="submit" raised on-click="_submit">Click!</paper-button>
      </form>
    </hot-form-validator>

Now, hot-form-validator needs to get the form, and then look -- within the form -- for a specific button (with type=submit). So, I have: (remember that this.form is the form):

attached: function(){
  var paperButton = this.form.$$('paper-button[type=submit]');
  ...
}

It works, but it doesn't make sense that it does since $$ should be only for local DOM, whereas paper-button is actually in the form's light DOM.

attached: function(){
  var paperButton = this.form.queryEffectiveChildren('paper-button[type=submit]');

This works, but I wonder if it's the best way to go.

Or... since there is no shadow DOM, should I simply no bother worrying about all this, and simply use DOM as always since there is no light/local DOM to deal with?

Upvotes: 3

Views: 1690

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657068

See https://www.polymer-project.org/1.0/docs/devguide/local-dom#light-dom-children

If you add an id to the <content id="someId"></content> then you can use

var result = this.getContentChildren('#someId');

and then look up the desired element in the result.

You could for example create a specific <content> tag for the submit button like

<dom-module ...>
  <template>
    ...
    <content></content>
    <content id="submitButton" select="paper-button[type=submit]"></content>
    ...
  </template>
</dom-module>

and then get the element using

var submitButton = this.getContentChildren('#submitButton')[0];

This code is working

this.form.$$('paper-button[type=submit]');

because this.$$ forwards to querySelectorAll(...) and in shady DOM encapsulation is just emulated and doesn't prevent querySelectorAll(...) to find other children than local DOM children.

You can also use

var submitButton = Polymer.dom(this).querySelector('paper-button[type=submit]');

Upvotes: 1

Related Questions