Bryan P Bryan P - 28 days ago 5
CSS Question

Handling button mdl-js styling with dynamic innerHTML change

Changing

<button>
innerHTML seems to deactivate mdl-js-ripple-effect.
Use the method mentioned here to dynamically build a new element as the workaround or report this as a bug?

<body>
<button id="myButton" class="mdl-button mdl-js-button mdl-js-ripple-effect">OLD VALUE
</button>
</body>


JS:

window.addEventListener("load", () => {
document.getElementById("myButton").innerHTML = "new value";

});


http://codepen.io/anon/pen/KVvMOE

Tried the
componentHandler.upgradeElement(button)
on the existing element after setting new html, but as mentioned in the docs it's only good for new ones. Trying to reuse existing elements.

Answer

I when the component is parsed and upgraded by the MDL script, a lot of extra attributes are added to the outer node, and extra HTML added inside. That means both that setting the innerHTML will remove some of the necessary markup inside and that the upgradeElement will fail because of the markup that was added to the outer node.

You should try de-upgrading the button with componentHandler.downgradeElements first, then set the innerHTML, then call componentHandler.upgradeElement.

Some untested sample code:

function setText(element,newtext){
    componentHandler.downgradeElements(element);
    element.innerHTML=newtext;
    componentHandler.upgradeElement(element);
}
setText(document.getElementById('myButton'),'new value');