Skip to content Skip to sidebar Skip to footer

Collapse Text Without Using Ids

I have made the following script to collapse text. I have a lot of these collapseable boxes on my site. Can I somehow make this without an ID? So you just get an a href tag that is

Solution 1:

You can use delegation for your case.

const container = document.querySelector("#container");

container.addEventListener("click", kadabra);

functionkadabra(event) {
  const section = event.target.closest("section");
  if (section !== null) {
    section.querySelector("div").classList.toggle("meerinfobox");
  }
}
.meerinfobox {
  display: none;
  padding-left: 16px;
}
<divid="container"><section><p><ahref="#">CLICK4MORE</a> Text Text</p><divclass="meerinfobox"><pre> Text text text text text text text </pre></div></section><section><p><ahref="#">CLICK4MORE</a> Text Text</p><divclass="meerinfobox"><pre>Text text text text text text text </pre></div></section><section><p><ahref="#">CLICK4MORE</a> Text Text</p><divclass="meerinfobox"><pre>Text text text text text text text </pre></div></section></div>

Solution 2:

If the html structure is as I see it, then you can use nextElementSibling

nextElementSibling

So basically your function becomes

functionkadabra(el) {
    let abra = el.nextElementSibling;

    if (abra.style.display == "block") {
      abra.style.display = "none";
    } else {
      abra.style.display = "block";
    }
  }

and you call it like this

<ahref="#"onclick="kadabra(this);">CLICK4MORE</a>

functionkadabra(el) {
        let abra = el.nextElementSibling;

        if (abra.style.display == "block") {
          abra.style.display = "none";
        } else {
          abra.style.display = "block";
        }
      }
.meerinfobox {
        display: none;
        padding-left: 16px;
      }
<divid="container"><section><ahref="#"onclick="kadabra(this)">CLICK4MORE</a> Text Text
    <divclass="meerinfobox"><pre> Text text text text text text text </pre></div></section><section><ahref="#"onclick="kadabra(this)">CLICK4MORE</a> Text Text
    <divclass="meerinfobox"><pre>Text text text text text text text </pre></div></section><section><ahref="#"onclick="kadabra(this)">CLICK4MORE</a> Text Text
    <divclass="meerinfobox"><pre>Text text text text text text text </pre></div></section></div>

Post a Comment for "Collapse Text Without Using Ids"