Collapsible button inside a ul list does work in jsfiddle but not in WP

I implemented a collapsible button, it works well in WP, but if I insert it in a ul list it doesn’t work, that is the button does not open.

Then I tried to run the code in jsfiddle and there it does work.

The only difference between the WP code and the jsfiddle code is in the javascript

  • on WP the var content is defined by this.parentElement.nextElementSibling;
  • on jsfiddle the var content is defined by this.nextElementSibling;

This is due to the fact that

  • by removing parentElement on WP the button will break
  • by adding parentElement on jsfiddle the button will break

Just for information, the javascript on WP is loaded in the footer.

Is it possibile to fix the problem? Here is the jsfiddle demo.


Below you can see jsfiddle vs WP

enter image description hereenter image description here


HTML FROM CHROME INSPECT TOOL

<div class="entry-content">
        <p>Does <button class="col">this</button> work?</p>
<div class="con space" style="">
<p>Yes!</p>
<p></p></div>
<hr>
<ul>
<li>Does <button class="col">this</button> work?
<div class="con space">
<p>Only in jsfiddle, not in WP!</p>
</div>
</li>
<li style="">another line</li>
</ul>
    </div>

HTML FROM WP CLASSIC EDITOR

Does <button class=col>this</button> work?
<div class="con space"><p>Yes!<p/></div>

<hr>

<ul>
  <li>Does <button class=col>this</button> work?
      <div class="con space"><p>Only in jsfiddle, not in WP!</p></div></li>
  <li>another line</li>
</ul>

The space class just contains margin-bottom: 1.5em;

1 Answer
1

Solution provided by Steven

<script type="text/javascript">
( function() {
    coll = document.getElementsByClassName("col");
    conn = document.getElementsByClassName("con");
    var i;
    for (i = 0; i < coll.length; i++) {
        coll[i].setAttribute('data-id', 'con' + i);
        conn[i].setAttribute('id', 'con' + i);
        coll[i].addEventListener("click", function() {
            this.classList.toggle("active");
            var content = document.getElementById(this.getAttribute('data-id'));
            if (content.style.maxHeight) {
                content.style.maxHeight = null;
            } else {
                content.style.maxHeight = content.scrollHeight + "px";
            }
        });
    }
} )();
</script>

Leave a Comment