Dynamically added accordion doesn't work

Need help to understand, how to get this code working.
Using accordion, when my html-code is “static”, it works as expected.
But if the html-code is added dynamically at run-time, with JS, accordions don’t work. I assume I need something to “activate” the accordion functionality. But what?
Please see below examples.
I’m using Foundation 6.5.1

This first example works, clicking “I” or “II” opens the corresponding contents:

<ul class='accordion' data-accordion>
  <li class='accordion-item is-active' data-accordion-item>
	<a href='#' class='accordion-title'>I</a>
	<div class='accordion-content' data-tab-content>
	  <p>Content 1</p>
  <li class='accordion-item' data-accordion-item>
	<a href='#' class='accordion-title'>II</a>
	<div class='accordion-content' data-tab-content>
	  <p>Content 2</p>

But the below example doesn’t work, clicking “I” or “II” does not open any contents:

<div id="myaccordion"></div>
<script src="assets/js/app.js"></script>
	$(function() {
		var e = document.getElementById('myaccordion');
		if( typeof e != 'undefined' ) {
			szHtml  = "<ul class='accordion' data-accordion>"
			szHtml += "  <li class='accordion-item is-active' data-accordion-item>"
			szHtml += "    <a href='#' class='accordion-title'>I</a>"
			szHtml += "    <div class='accordion-content' data-tab-content>"
			szHtml += "      <p>Content 1</p>"
			szHtml += "    </div>"
			szHtml += "  </li>"
			szHtml += "  <li class='accordion-item' data-accordion-item>"
			szHtml += "    <a href='#' class='accordion-title'>II</a>"
			szHtml += "    <div class='accordion-content' data-tab-content>"
			szHtml += "      <p>Content 2</p>"
			szHtml += "    </div>"
			szHtml += "  </li>"
			szHtml += "</ul>"

			e.innerHTML = szHtml

You need to initialize it…


Indeed, that was simple. I don’t know how I missed it.
Thank you very much for answering my entry level question.

1 Like