5

I have the following code,

var loginForm = document.createElement('div');

loginForm.className = 'row';

loginForm.innerHTML = '<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label textfield-demo"><input class="mdl-textfield__input" type="text" id="login" /><label class="mdl-textfield__label" for="login">Username</label></div>';

document.getElementById('page-content').appendChild(loginForm);

The problem is that since the javascript functions have already ran the input is not styled correctly.

Does anyone what javascript function I need to call to make this work? I tried MaterialTextfield.prototype.init() but nothing changed.

Grady D
  • 1,889
  • 6
  • 30
  • 61

2 Answers2

8

You can use MDL's upgrading element function. Since you have created the loginForm dynamically, you can upgrade it in scope with

    componentHandler.upgradeElement(loginForm);
    //or, componentHandler.upgradeDom(loginForm);
    //however, I suggest using jQuery to upgrade multiple if you are adding more than one
    componentHandler.upgradeElements($('.mdl-textfield').get());

This will get all the mdl-textfield objects and upgrade them (if not upgraded before)

Ivan Chau
  • 96
  • 1
  • 2
2

I kept digging through the source code and found componentHandler.upgradeDom(). When running this function all of the dynamic elements are fixed.

Grady D
  • 1,889
  • 6
  • 30
  • 61