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

Column alignment issue detected

Can you help me with aligning the data in my column status properly? Whenever I update the data, it doesn't align correctly as shown in the first image. https://i.stack.imgur.com/300Qt.png https://i.stack.imgur.com/4Dcyw.png $('#btn_edit' ...

Utilize CSS to specifically target the image source within a button and swap it with a different image in the Woocommerce Wishlist Plugin on your Wordpress

I have integrated the Woocommerce Wishlist plugin into my Wordpress website and I am looking to customize the appearance of the 'Add to Wishlist' button. Upon inspecting the source code, I noticed that the button is styled with a GIF image. I wou ...

Parse the JSON file and assign the arrays to your GO variables

I've been given the challenging task of migrating my project from Python to Go, but I've hit a roadblock that's been consuming hours of my time. Within my project, there exists a file named data.json which houses the following information: ...

The CSS dropdown menu is malfunctioning on Internet Explorer and Firefox

After searching for a solution and coming up empty-handed, I have decided to ask a question. The drop-down menu on my computer and other devices at home works perfectly in Chrome but not in Firefox and IE. #menu { position: absolute; left: 50%; bottom ...

Tips for obtaining a JSON response from a RESTful API in AngularJS by utilizing the $resource service

I have been working on my AngularJS code, and although I am receiving a response in the console, I am having trouble storing it in an array or JSON format. angular.module('user', ['ngResource']). config(function($httpProvider){ $h ...

Using a jQuery gallery can cause links to become unresponsive and unclickable

While creating a responsive webpage with the Zurb Foundation framework, I encountered an issue when trying to incorporate nanoGallery which also uses jQuery. After adding the gallery scripts, the top menu generated by the Foundation script became unclickab ...

Mastering various mathematical operations in Vue.js

I am attempting to calculate the percentage of a value and then add it back to the original value using Vue.js. Here is an example: 5 / 100 * 900 + 900 = 945.00 (standard calculation) 5 / 100 * 900 + 900 = 90045 (Vue.js calculation) This is the code I ha ...

Tips for successfully transmitting an HTML form array using jQuery's .post method

Looking for assistance with using $.post() method to send form data. Here is an example of a simplified form containing a multi-dimensional array: <form action="save-objectives.php" name="save-objectives-form" id="save-objectives-form"> <input ...

In a multidimensional array, locate the key corresponding to the specified value

I am facing an issue with my code that involves an array containing various fruits with product ID and price as keys for different values. While I am able to retrieve the correct price, I am struggling to get the name of the chosen product. For instance, ...

Creating a Smooth Curve with CSS

Recently, I've decided to create a unique clock design inspired by the one showcased here. However, instead of using images like they did, I would like to implement ARC. Is it possible to create an arc using only CSS? For instance, if I wanted to make ...

What is the best way to add a dynamic parameter to the URL?

Here is an example of my URL: https://my-website.com/api/players?countryId=1&clubId=2&playerName=abc The parameter values can vary. This is the code snippet I use: getDataPlayer(payload) { let params if(payload.countryId && payl ...

Angular UI-Router: Difficulty in Child State Accessing Parent Controller

I am currently using ui.router's nested views feature in my Angular application. Here is the relevant part of my .config: $urlRouterProvider.otherwise('/'); $stateProvider .state('home', { url: '/', templateUrl: ...

Organizing dates with Javascript

Is there a way to convert a string from this format : 2014-06-12T23:00:00 To another format using JavaScript, like so : 12/06/2014 23:00 ...

Discover how to use your own search engine suggestions within the search bar of Google Chrome

I recently created a search engine on my website, and everything seems to be working perfectly when I visit the search page. However, I wanted to streamline the process by searching directly from the search box in Chrome. After adjusting the settings to ...

Loading the Facebook JavaScript SDK asynchronously using React and Redux

I have a process that involves loading a JavaScript SDK, which looks like this: class Facebook{ constructor(){ window.fbAsyncInit = () => { FB.init({ appId : 'myappID', ...

Tips on formatting text as bold or italic when tweeting from my website to our Twitter account

Currently, I am utilizing the Twitter OAuth library in conjunction with PHP to publish a tweet from my website directly to my Twitter account. My main objective is to highlight some text while posting, however, I have not been successful in identifying t ...

Minimize a pop-up window and navigate to a different webpage

I have created a login/logout form that includes the option to delete my account. When I click the "Sterge cont" button, a pop-up window appears asking if I truly want to delete the account. If I select "NU," the account will not be deleted and the window ...

having difficulty accessing the value within the Angular constructor

My current issue arises when I click on a button and set a value within the button click method. Despite declaring the variable in the constructor, I am unable to retrieve that value. The code snippet below demonstrates this problem as I keep getting &apos ...

how to handle form submission using JavaScript's return method

As a developer, I have created a single page that fetches data from a registration page. On this page, each data row has an "add" and "unfriend" button, with the latter initially disabled. When a user clicks the "add" button, a prompt box appears asking ...

Issue: Unable to find solutions for all parameters in NoteService: (?)

After following a tutorial on Angular 2 from , I encountered the mentioned error when running my API. The browser indicates that there are unresolved parameters in the following service: import {Injectable} from '@angular/core'; import { ApiSe ...