componentHandler.upgradeDom() in material-design-lite with for loop

2.7k views Asked by At

I am using material design lite and inserting elements with for loop.

var insertClass ='';
var classlist = document.querySelector('.classList');
for (var i = 0; i < 5; i++) {
    insertClass += '<div class="eachClass">' +
                      '<p>'+ i +'</p>' +
                     '<button id="demo-menu-lower-right" class="mdl-button mdl-js-button mdl-button--icon">'+
                       '<i class="material-icons">more_vert</i>'+
                     '</button>' +
                     '<ul class="mdl-menu mdl-menu--bottom-right mdl-js-menu mdl-js-ripple-effect" for="demo-menu-lower-right">' +
                       '<li class="mdl-menu__item deleteClass">Delete</li>' +
                       '<li class="mdl-menu__item editClass">Edit</li>' +
                     '</ul>' +
                  '</div>';
}
classlist.innerHTML = insertClass;
componentHandler.upgradeAllRegistered('MaterialMenu', 'mdl-js-menu');

The componentHandler.upgradeAllRegistered() function is not working at all, but when I use upgradeDom() it will work only on first element.

1

There are 1 answers

0
indigoi On BEST ANSWER

In the example you have provided, you are going to end up with multiple buttons with the same id and multiple ul menus with the same for. That would potentially explain why you appear to only get one menu as the id and for are used by material design lite to bind the buttons and menus together. Try rewriting your example with:

'<button id="demo-menu-lower-right_' + i + '" class="mdl-button mdl-js-button mdl-button--icon">'+
   '<i class="material-icons">more_vert</i>'+
'</button>' +
'<ul class="mdl-menu mdl-menu--bottom-right mdl-js-menu mdl-js-ripple-effect" for="demo-menu-lower-right_' + i + '">' +
   '<li class="mdl-menu__item deleteClass">Delete</li>' +
   '<li class="mdl-menu__item editClass">Edit</li>' +
 '</ul>'

...which will give each button and menu a unique id or for.