How do I call methods on a custom element that I get from the DOM?

124 views
Skip to first unread message

bo...@jadedpixel.com

unread,
Dec 17, 2013, 3:53:50 PM12/17/13
to polym...@googlegroups.com, Harry Brundage
For example, if I do something like this: 

div = document.createElement('div');

div
.innerHTML = "<custom-element/>";
element
= div.querySelector(":first-child");


element
.update(); // how do I call the update method on my custom element?

Another example would be selecting a custom element in Chrome in the inspector, and calling something on that element using $0 in the console. It doesn't seem to work for me. I followed the instruction on how to create a custom element here: http://www.polymer-project.org/platform/custom-elements.html

Daniel Freedman

unread,
Dec 17, 2013, 4:10:31 PM12/17/13
to polym...@googlegroups.com, Harry Brundage, bo...@jadedpixel.com
Looks like you've hit the corner cases of the Custom Elements and ShadowDOM polyfills that Polymer uses.
I'll answer your two cases separately.

In the first case, the Custom Elements polyfill can only automatically upgrade elements after they've been inserted into the document, or have been created with document.createElement.
In your case, I suggest you do 

div.appendChild(document.createElement('custom-element'));

element
= div.querySelector(':first-child');

element
.update();

If you have some system that depends on using innerHTML, you have a few alternatives

div.innerHTML = '<custom-element></custom-element>';
// trigger polyfill upgrade directly
element
= CustomElements.upgrade(div.querySelector(':first-child'));
element
.update();

// or put the div in the document and let the element upgrade automatically
document
.body.appendChild(div);
// wait for Custom Elements polyfill to run (using a Mutation Observer);
requestAnimationFrame(element.update);

// or put the div in the document and force the element to upgrade synchronusly.
CustomElements.takeRecords();
element
.update();


As for ShadowDOM Polyfill, the problem is that there is no hook for the devtools "$0" magic, so we can't provide the correct ShadowDOM polyfill magic wrapper (SD has to wrap DOM API calls).

You can get the wrapper manually by calling

ShadowDOMPolyfill.wrap($0)

// Polymer exposes this as window.wrap


As these features come out from behind flags in Chrome, and are implemented in other browsers, these corner cases will fall away and you won't have to think about them :).


Reply all
Reply to author
Forward
0 new messages