How to convert this jQuery snippet to vanilla JavaScript?

Hi,

While I’m learning JavaScript, I started to work on the following example

https://codepen.io/itsthomas/pen/wxwRYx?editors=1010

The script sends an Ajax call and gets back a simple JSON file.
I fetch the response and build a simple unordered list using Handlebars.js.
So far so good.

Now I wanted that if I click on the button in front of each character, a hidden div becomes visible, which contains some details about the character.
I achieved this easily using jQuery.
However, I spent a whole day to convert that small jQuery snippet to vanilla JS and failed badly. :frowning:

How can I change the jQuery snippet, which shows and hides the div to vanilla JS?
It’s not important if it slides or not. It would be enough if I could just show and hide it by adding the class visible to it.

This is the jQuery code, I want to convert to vanilla JS:

// jQuery solution using event delegation for slideToggle
$('#container').on('click', 'button.btn', function() {
  console.log($(this)); // this is the button with the class btn

  // If the button is clicked, add a class to .details
  $(this).parent().parent().next($('.details')).slideToggle();
})
// $('#container').on('click', 'button.btn', function() {
document.querySelector("#container").addEventListener("click", function (evt) {
    var target = evt.target;
    if (target.nodeName === "BUTTON" && target.classList.contains("btn")) {
    // console.log($(this)); // this is the button with the class btn
    console.log(target);
    // $(this).parent().parent().next($('.details')).slideToggle();
    target.parentNode.parentNode.querySelector(".details").classList.toggle("slide");
    }
});

The presentation details of sliding the element I leave for CSS to achieve.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.