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);

function kadabra(event) {
  const section = event.target.closest("section");
  if (section !== null) {
    section.querySelector("div").classList.toggle("meerinfobox");
  }
}
.meerinfobox {
  display: none;
  padding-left: 16px;
}
<div id="container">
  <section>
    <p><a href="#">CLICK4MORE</a> Text Text</p>
    <div class="meerinfobox">
      <pre> Text text text text text text text </pre>
    </div>
  </section>
  <section>
    <p><a href="#">CLICK4MORE</a> Text Text</p>
    <div class="meerinfobox">
      <pre>Text text text text text text text </pre>
    </div>
  </section>
  <section>
    <p><a href="#">CLICK4MORE</a> Text Text</p>
    <div class="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

  function kadabra(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

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

      function kadabra(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;
      }
<div id="container">
  <section>
    <a href="#" onclick="kadabra(this)">CLICK4MORE</a> Text Text
    <div class="meerinfobox">
      <pre> Text text text text text text text </pre>
    </div>
  </section>
  <section>
    <a href="#" onclick="kadabra(this)">CLICK4MORE</a> Text Text
    <div class="meerinfobox">
      <pre>Text text text text text text text </pre>
    </div>
  </section>
  <section>
    <a href="#" onclick="kadabra(this)">CLICK4MORE</a> Text Text
    <div class="meerinfobox">
      <pre>Text text text text text text text </pre>
    </div>
  </section>
</div>

Post a Comment for "Collapse Text Without Using IDs"