Search code examples
javascriptconditional-statementssiblings

How to create curriculum presentation for a course with JavaScript?


I would like to create a curriculum presentation by Java Script similar to the one on Udemy.

https://prnt.sc/22zxxrp

I have tried to put both button and content in the same div and to add an event listener which would on click trigger conditional check if both of the elements are of the same parent and if true to display the content.

But it does not work.

The code would be something like this but with more buttons.

   let batonceros  = document.getElementsByClassName("batno");

   let paragraph = document.getElementsByClassName("para");



   batonceros.addEventListener("click", function() {

   if( batonceros != paragraph && batonceros.parentNode == paragraph.parentNode) {
    
    batonceros.style.display = "block";
}

else {
    batonceros.style.display = "none";
    
  }
 });

Solution

  • Not exactly sure what you're trying to accomplish, but maybe this might help. It shows how to reference the parent container to find the relative .para from its .batno

    let batonceros = document.querySelectorAll(".batno");
    let paragraph = document.querySelectorAll(".para");
    
    batonceros.forEach(button => button.addEventListener("click", e => {
      e.target.closest('div').querySelector('.para').classList.toggle('show');
    }));
    .para {
      display: none;
    }
    
    .show {
      display: block;
    }
    <div>
      <p class='para'>This is a paragraph</p>
      <button class='batno'>Button</button>
    </div>
    
    <div>
      <p class='para'>This is a paragraph</p>
      <button class='batno'>Button</button>
    </div>