4

How do I get the width of a custom element from the element's script?

<polymer-element name="his-elem">
  <div>
    blah
  </div>
</polymer-element>

@CustomTag('his-elem')
class blah extends PolymerElement {

  @override
  void attached() {
    // how do I get the <his-elem>'s width (just width, no padding border stuff) here?
    // document.querySelector('his-elem').getComputedStyle().width gives me "auto"...
  }

}

Update

Add :host {display: block;} to his-element, then you can get the actual width via <his-elem>.clientWidth.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Not an ID
  • 2,579
  • 2
  • 21
  • 28

2 Answers2

2

I use this when the other methods don't work:

this.getBoundingClientRect().width

See also https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect

**In Polymer <= 0.16

you need to call super.attached() previously

  @override
  void attached() {
    super.attached();
    print(this.getBoundingClientRect().width);
    // or 
    print(this.getComputedStyle().width);
  }

before the call to super.attached() the element isn't yet attached to the DOM and won't return a proper width. Actually with overriding attached and not calling super.attached() within the method you prevent attaching.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
1

this represents the html element itself. So it should be this.style.width.

Gérald Reinhart
  • 3,101
  • 1
  • 13
  • 14