What is the best way to show and hide the information in a FAQ section when each one is clicked?

const faqItems = document.getElementsByClassName("faq-question");
            const faqContents = document.getElementsByClassName("faq-content");

            for (item of faqItems) {
                console.log(item);

                item.addEventListener('click', () => {
                    for(content of faqContents){
                        console.log(content)
                    };
                })   
         
.faq {
               display: flex;
               flex-direction: column;
               justify-content: center;
               align-items: center;
               margin: 0 auto;
               padding: 60px 90px;
               background-color: black;
               border-bottom: 10px solid #222;
               color: white;
            }
         ...
         .email-2 input {
            width: 68%;
         }
<section class="faq">
                     <h1 class="faq-title"> Frequently Asked Questions </h1>
                  ...
         

I need assistance in modifying the code to show only the specific content related to each FAQ item when clicked on. Currently, clicking on any button displays all contents instead of just the one linked to the corresponding question. How can I achieve this functionality?

const faqItems = document.getElementsByClassName("faq-question");
            const faqContents = document.getElementsByClassName("faq-content");

            for (item of faqItems) {
                console.log(item);

                item.addEventListener('click', () => {
                    for(content of faqContents){
                        console.log(content)
                    };
                })   
         
:root {
               --red: #e50914;
            }
            ...
            .footer {
               ...
            }
<!DOCTYPE html>
                     <html lang="en">
                        <head>
                           ...
                        </head>
                     <body>
                        <main>
                           <div class="front-page">
                              ...
                           </div>
                           ...
                        </main>
                        <script src="/main.js"></script>
                     </body>
                     </html>

Answer №1

To simplify your code, consider utilizing the summary and details attributes as demonstrated in the example provided:

<details>Apple Music is a music streaming service
     <summary>Apple Music</summary>
</details>

Answer №2

You have the option to manually assign CSS styles through JavaScript, toggling between display: block and display: none

const faqItems = document.getElementsByClassName("faq-question");
const faqContents = document.getElementsByClassName("faq-content");

for (item of faqItems) {
  
  item.addEventListener('click', (e) => {
    // CLOSE ALL FAQS
    for (let i=0; i<faqContents.length; i++) {
      faqContents[i].style.display = 'none'
    }

    // OPEN THE CLICKED FAQ
    e.target.nextSibling.nextSibling.style.display = 'block'
  })
  
}
.faq {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
  padding: 60px 90px;
  background-color: black;
  border-bottom: 10px solid #222;
  color: white;
}

.faq-title {
  font-size: 50px;
  line-height: 55px;
  font-weight: 700;
  color: white;
  text-align: center;
}

.faq-list {
  width: 65%;
  text-decoration: none;
  list-style: none;
}

.faq-item {
  display: block;
  margin-bottom: 10px;
}

.faq-question {
  width: 100%;
  text-align: left;
  border: 0;
  margin-bottom: 2px;
  position: relative;
  background-color: #303030;
  color: white;
  font-weight: 500;
  font-size: 25px;
  padding: 25px;
  cursor: pointer;
}

.faq-question svg {
  width: 40px;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  right: 16px;
  cursor: pointer;
}

.faq-question svg path {
  fill: white;
}

.faq-content {
  display: block;
  text-align: left;
  border: 0;
  margin-bottom: 2px;
  background-color: #303030;
  color: white;
  font-weight: 500;
  font-size: 25px;
  padding: 25px;
  display: none;
}

.member h2 {
  font-size: 20px;
  font-weight: 400;
  text-align: center;
}

.member .email-2 {
  width: 100%;
  display: flex;
  margin-top: 30px;
}

.email-2 input {
  width: 68%;
}
<section class="faq">
  <h1 class="faq-title"> Frequently Asked Questions </h1>

  <ul class="faq-list">
    <li class="faq-item">
      <button class="faq-question">
                        What is Netflix?
                        <svg xmlns="http://www.w3.org/2000/svg" height="48" width="48"><path d="M23.25 37V24.75H11v-1.5h12.25V11h1.5v12.25H37v1.5H24.75V37Z"/></svg>
                    </button>
      <div class="faq-content">
        <article>
          Netflix is a streaming service that offers a wide variety of award-winning TV shows, movies, anime, documentaries, and more on thousands of internet-connected devices. <br> You can watch as much as you want, whenever you want without a single
          commercial – all for one low monthly price. There's always something new to discover and new TV shows and movies are added every week!
        </article>
      </div>
    </li>

    <li class="faq-item">
      <button class="faq-question">
                        How much does Netflix cost ?
                        <svg xmlns="http://www.w3.org/2000/svg" height="48" width="48"><path d="M23.25 37V24.75H11v-1.5h12.25V11h1.5v12.25H37v1.5H24.75V37Z"/></svg>
                    </button>
      <div class="faq-content">
        <article>
          Watch Netflix on your smartphone, tablet, Smart TV, laptop, or streaming device, all for one fixed monthly fee. Plans range from ₦1,200 to ₦4,400 a month. No extra costs, no contracts.
        </article>
      </div>
    </li>

    <li class="faq-item">
      <button class="faq-question">
                        Where can I watch?
                        <svg xmlns="http://www.w3.org/2000/svg" height="48" width="48"><path d="M23.25 37V24.75H11v-1.5h12.25V11h1.5v12.25H37v1.5H24.75V37Z"/></svg>
                    </button>
      <div class="faq-content">
        <article>
          Watch anywhere, anytime. Sign in with your Netflix account to watch instantly on the web at netflix.com from your personal computer or on any internet-connected device that offers the Netflix app, including smart TVs, smartphones, tablets, streaming media
          players and game consoles. <br> You can also download your favorite shows with the iOS, Android, or Windows 10 app. Use downloads to watch while you're on the go and without an internet connection. Take Netflix with you anywhere.
        </article>
      </div>
    </li>

    <li class="faq-item">
      <button class="faq-question">
                        How do I cancel?
                        <svg xmlns="http://www.w3.org/2000/svg" height="48" width="48"><path d="M23.25 37V24.75H11v-1.5h12.25V11h1.5v12.25H37v1.5H24.75V37Z"/></svg>
                    </button>
      <div class="faq-content">
        <article>
          Netflix is flexible. There are no pesky contracts and no commitments. You can easily cancel your account online in two clicks. There are no cancellation fees – start or stop your account anytime.
        </article>
      </div>
    </li>

    <li class="faq-item">
      <button class="faq-question">
                        What can I watch on Netflix?
                        <svg xmlns="http://www.w3.org/2000/svg" height="48" width="48"><path d="M23.25 37V24.75H11v-1.5h12.25V11h1.5v12.25H37v1.5H24.75V37Z"/></svg>
                    </button>
      <div class="faq-content">
        <article>
          Netflix has an extensive library of feature films, documentaries, TV shows, anime, award-winning Netflix originals, and more. Watch as much as you want, anytime you want.
        </article>
      </div>
    </li>

    <li class="faq-item">
      <button class="faq-question">
                        Is Netflix good for kids?
                        <svg xmlns="http://www.w3.org/2000/svg" height="48" width="48"><path d="M23.25 37V24.75H11v-1.5h12.25V11h1.5v12.25H37v1.5H24.75V37Z"/></svg>
                    </button>
      <div class="faq-content">
        <article>
          The Netflix Kids experience is included in your membership to give parents control while kids enjoy family-friendly TV shows and movies in their own space. <br> Kids profiles come with PIN-protected parental controls that let you restrict the
          maturity rating of content kids can watch and block specific titles you don’t want kids to see.
        </article>
      </div>
    </li>
  </ul>

  <div class="member">
    <h2>Ready to watch? Enter your email to create or restart your membership.</h2>

    <div class="email-2">
      <input type="text" placeholder="Email Address">

      <button class="get-started">
                        Get Started
                    </button>
    </div>
  </div>
</section>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Despite containing elements, Array.length incorrectly reports as 0 in React, JavaScript, and TypeScript

I have been working on storing persistent data for my Electron app using electron-json-storage. Initially, I tried using neDB but encountered an error, so I switched to another method. However, it seems that the issue is not with neDB but rather with my ow ...

A guide on setting up a countdown timer in Angular 4 for a daily recurring event with the help of Rxjs Observable and the Async Pipe

I'm currently working on developing a countdown timer for a daily recurring event using Angular 4, RxJS Observables, and the Async Pipe feature. Let's take a look at my component implementation: interface Time { hours: number; minutes: numbe ...

Connecting with Node JS, utilising the power of Socket.IO, Express, and establishing

Hey everyone, I have an interesting concept that I'd like to discuss with you to get your thoughts on its feasibility. The idea is to set up an RFID reader connected to a MacMini (with the Mini hidden and only the RFID visible). An iPad would also be ...

Gitbook is facing a unique challenge with the Chinese language in its HTML code - an issue with excessive spacing

Currently, I am utilizing gitbook and github pages to construct my personal webpage with the main language being Chinese. However, I have noticed that gitbook is adding an extra space in some places where it is unnecessary. Below is the text found in the m ...

Creating a stylish touch by connecting list items with a horizontal line in a menu

I have a Menu where each item has an image, and I am looking to connect those images with a horizontal line. <ul> <li> <a href="#" title="Item1"><img src="foo/bar.png"></a> </li> <li> & ...

Maintain the visibility of the jQuery dropdown menu even when navigating to a different page within the

I am experiencing an issue with my dropdown menu. Whenever I click on a "dropdown link", it opens another page on my website, but the menu closes in the process. I want to ensure that the menu stays open and highlights the clicked "dropdown link" in bold. ...

Encountered an error: "Type error undefined" while attempting to populate a form using AJAX and JSON

Upon inspecting the development console, it's clear that my AJAX request was successful and I've received the necessary JSON data. However, I'm struggling to display it correctly as I keep encountering the error below: Uncaught TypeError: C ...

Upgrade to the latest version of MaterialUI - V4

After attempting to upgrade materialUI/core from version 3.9.3 to 4.4.1 and materialUI/icons from version 3.0.2 to 4.4.1, I encountered the following error: Error: TypeError: styles_1.createGenerateClassName is not a function I am currently importing crea ...

Can a Jquery *compiler* be developed?

Upon encountering this informative question, the idea of creating a jQuery compiler crossed my mind. The concept was to design a tool that could translate jQuery code into raw JavaScript code for execution. In my imagination, the process of executing a bl ...

What is the best way to filter two tables using only one search bar?

In my Vue2 application, I have implemented a pair of data tables on one of the pages. Each table is placed behind a tab, allowing users to choose which one they want to view. The search bar, however, is not confined within a tab as I wanted to avoid duplic ...

What is the best way to extract values from this PHP script?

I recently delved into the d3 javascript library and successfully created a scatter plot chart that pulls random values from an array. Below is the code snippet: <!DOCTYPE html> <meta charset="utf-8"> <head> <script type="text/ja ...

Obtain information using AJAX calls with jQuery Flot

Having an issue with jQuery Flot that I need help resolving. PHP output (not in JSON format): [[1, 153], [2, 513], [3, 644]] ~~ [[1, 1553], [2, 1903], [3, 2680]] Here is the jQuery call: $.ajax({ url: 'xxx.php', success: function (dat ...

What is the best way to incorporate an image zoom-in effect into a flexible-sized block?

Having a fluid grid with 3 blocks in one row, each set to width:33.3%. The images within these blocks are set to width: 100% and height: auto. I am looking to implement a zoom-in effect on hover for these images without changing the height of the blocks. I ...

I am facing an issue with submitting a form using jQuery POST and php serialization

I am struggling to send form data using jQuery. The data seems to be stuck in a loop where it keeps requesting the page ./?page=game&mode=search&type=private with the GET function and does not reach the server. Can someone help me identify what I m ...

Is <form> tag causing code deletion after an ajax request?

I'm working on a form that looks like this: <form> <input class="form-control" id="searchField" type="text"> <button type="submit" id="searchUserButton">SEARCH BUTTON</button> </form> When I click on SEARCH BUT ...

Increase the spacing between the scrollbar and the border

Looking to create some breathing room between the scrollbar and the right border of my text area. I've tried adjusting the margin-right/left values in -webkit-scrollbar with no success. Here's my style component: const FormTextArea = styled.texta ...

What is the importance of always catching errors in a Promise?

In my project, I have implemented the @typescript-eslint/no-floating-promises rule. This rule highlights code like this - functionReturningPromise() .then(retVal => doSomething(retVal)); The rule suggests adding a catch block for the Promise. While ...

Struggling to Align NAV buttons to the Right in React Framework

My current Mobile Header view can be seen here: https://i.stack.imgur.com/CcspN.png I am looking to achieve a layout similar to this, https://i.stack.imgur.com/pH15p.png. So far, I have only been able to accomplish this by setting specific left margins, ...

I am receiving all NFT IDs when I should only be getting the ones that are associated with the current account

I am facing an issue where I am receiving all NFTs token IDs instead of just the one that belongs to the current account. The code snippet causing this problem is as follows: const { enableWeb3, account, isWeb3Enabled, Moralis, deactivateWeb3 } = useMorali ...

Error in Node application: Cannot search for 'x' in 'y' using the 'in' operator with Express and Nunjucks

Hello everyone, I am a beginner in the world of Nunjucks/Express and Node.js. I have a routes file that is capturing the value of an input from a form field. My goal is to check if this value contains the string 'gov'. Here is what my code look ...