Search code examples
javascriptjquerymaterialize

Materialize: Make collapsible-header active via js/jquery


Trying to add an item to my Materialize accordion dynamically from js and want to make that one active immediately. Tried using this:

var accordion = $('#accordion');
accordion.append('<li><div class="collapsible-header active"><i class="material-icons">whatshot</i>Third</div><div class="collapsible-body"><p>Lorem ipsum dolor sit amet.</p></div></li>');

Element gets added but isn't active. Also tried this after the previous two lines:

accordion.children().last().addClass('active');

also did not work.


Solution

  • You can use collapsible() to update the accordion after change:

    var accordion = $('#accordion');
    accordion.append('<li><div class="collapsible-header active"><i class="material-icons">whatshot</i>Third</div><div class="collapsible-body"><p>Lorem ipsum dolor sit amet.</p></div></li>');
    accordion.collapsible();