Switch between display modes by clicking using collections

I am trying to figure out how to create a function that will only show content for the specific element in which my button is located. Currently, when I click the button it shows content for all elements with the 'one' class, but I want it to display content only for the related element.

I have attempted to assign a class to buttons and loop through them, however, I am struggling to understand how to achieve this.

function specificButtonFunction(){
    
    let x = document.getElementsByClassName("one");

    for(i=0; i<x.length; i++){
        
        if (x[i].style.display === "block") {
            x[i].style.display = "none";
          } else {
            x[i].style.display = "block";
          }
    }
    
   
};
.one{
    display: none;
}
<h1>Testing</h1>
        <div class="one">
            <p>Some text</p>
        </div>
        <button onclick="specificButtonFunction()">Show more!</button>
    </div>
    <div>
        <h1>Testing</h1>
        <div class="one">
            <p>Some other text</p>
        </div>
        <button onclick="specificButtonFunction()">Show more!</button>
    </div>

Answer №1

To easily toggle the visibility of elements with the class 'one' when clicking on buttons, you can loop through all the buttons and attach an event listener to each one.

document.querySelectorAll('.open-btn').forEach(btn =>
  btn.addEventListener('click', e => {
    btn.parentElement.querySelector('.one').classList.toggle('hide');
  })
);
.hide {
  display: none;
}
<div>
  <h1>Testing</h1>
  <div class="one hide">
    <p>Some text</p>
  </div>
  <button class="open-btn">Show more!</button>
</div>
<div>
  <h1>Testing</h1>
  <div class="one hide">
    <p>Some other text</p>
  </div>
  <button class="open-btn">Show more!</button>
</div>

Another approach is using event delegation by attaching the event listener to a static ancestor element (preferably closer than using document).

document.addEventListener('click', e => {
  if (e.target.matches('.open-btn')) {
    e.target.parentElement.querySelector('.one').classList.toggle('hide');
  }
});
.hide {
  display: none;
}
<div>
  <h1>Testing</h1>
  <div class="one hide">
    <p>Some text</p>
  </div>
  <button class="open-btn">Show more!</button>
</div>
<div>
  <h1>Testing</h1>
  <div class="one hide">
    <p>Some other text</p>
  </div>
  <button class="open-btn">Show more!</button>
</div>

Answer №2

  1. Enclose all content within a designated element¹ and set it to trigger the "click" event. In this instance, a <main> element is utilized. Once a click occurs on the <nain>, the event handler toggleDiv is invoked.

    const main = document.querySelector("main");
                
    main.addEventListener("click", toggleDiv);
    
  2. The functionality of the event handler toggleDiv is such that it filters the "click" event to specific elements while disregarding others. Here, only clicked <buttons> will respond. Refer to the comments in the example for further intricacies.

  3. This coding paradigm is known as event delegation. It involves a single element² listening for a triggered event registered either on itself or any nested component. The range of elements³ reacting to a directly activated registered event can be comprehensive (e.g., div), precise (e.g., #IdOfElement), or anything in between (e.g., .classNameOfElements). The quantity of such elements is unlimited, and dynamically added elements are also covered. Hence, having eventListeners for every element at creation or page load isn't necessary.

¹Element/Object can refer to <body>, <html>, document, or even window.

²event.currentTarget

³event.target

Example

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

Display list items in HTML based on the length of an array

In my backend, I have a user-defined array of cars. If the user selects 3 cars, the array will contain 3 elements. I would like to display specific details of the cars in HTML elements within a list. The array is based on JavaScript. Here is an example of ...

Facing Problem with Angular PUT Request - "Missing required request body"

I'm encountering a problem with my Angular application when attempting to send a PUT request to the server. The error message I receive reads "Required request body is missing." Below is a snippet of the code that is relevant: Within the Child Compo ...

An unusual occurrence with the setTimeOut function within a for loop was observed

When attempting to log numbers at specific intervals on the console, I encountered an unexpected issue. Instead of logging each number after a set interval, all numbers are logged out simultaneously. I've experimented with two different approaches to ...

Various redirects based on multiple referrers

Here is the code I have for redirecting based on the referer: document.addEventListener('DOMContentLoaded', function() { console.log(isMobile); var referrer = document.referrer; if(referrer.indexOf('site1.com') !== -1 || referrer ...

How can I generate two directory-based slider instances?

Update: Finally, I discovered the root of the problem within my stylesheet. Despite both sliders being loaded, they were overlapping due to their positioning, causing the second slider (or any additional ones) to remain hidden. I've been striving to ...

Incorporating additional information into the database

When I run the code, I see a table and a button. After entering data in the prompts as instructed, the table does not get updated. I'm unsure why this is happening. Can someone please explain? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Trans ...

Converting 2D pixel art into 3D coordinates with ThreeJS

Attempting to display a cube generated in ThreeJS on an HTML canvas at a specific location has been quite challenging. The location is defined in pixels, for example (100,200). Unfortunately, the process of converting these pixel values into ThreeJS coord ...

"Enhance your webpage with a captivating opaque background image using Bootstrap

I'm new to exploring Bootstrap and I am currently experimenting with options for displaying content with a semi-transparent background image. Currently, I am using a "well" but I am open to other suggestions. I have managed to place the image inside t ...

Utilizing "Content" for Responsive Image Design in Chrome Version 33.0.1750.117

I previously implemented a method for responsive images on my website, which was working fine until the latest Chrome update. Surprisingly, it still functions properly on other browsers. //< ![CDATA[ var queries = [ ...

What causes images to shift when resizing in Chrome, but not in Firefox or Safari?

My layout includes images - one on the left and two on the right. As I resize the browser window, the images scale accordingly. The issue arises when viewing my layout in Chrome: the image positions shift as I resize the browser, unlike Safari and Firefox ...

React hitting recursion limit due to excessive shouldComponentUpdate checks

I'm currently developing a real-time updating dashboard using React. The data for the dashboard components is fetched via an Ajax call and then passed to each component successfully. However, I encountered an issue with one specific component that re ...

display data labels within the chart - utilizing the power of angular.js in conjunction with chart.js

My goal is to display the chart's information without requiring the user to hover over any part of the chart. I am utilizing Chart.js with Angular.js I have the same question as this one posted here: question here! html code: <div class="wrapper ...

What sets React$Element apart from ReactElement?

Attempting to implement flow with ReactJS and needing to specify types for prop children. The article on Flow + React does not provide any information. Despite encountering examples using ReactElement (e.g), I received an error message from flow stating i ...

Saving information in node.js

My latest project involves creating an address book app using HTML, CSS, and JavaScript. The company provided me with a zip file containing the necessary resources to implement the app using node.js. However, my knowledge of node.js is limited and I have ...

Efficient Techniques for Concealing and Revealing Navigation Menus using HTML, CSS, and JavaScript

I need help making the menu icon toggle the navigate menu between showing and hiding when clicked on the top right corner of the screen. For better understanding, here is an accompanying image: https://i.stack.imgur.com/oy6d9.png However, the current co ...

Stop menu items from shifting when focused

I've developed a mobile hamburger menu and attempted to adjust the padding to create space between the text and the borders. Here's the HTML: #menu-solutions:hover .menu-item-text, #menu-solutions:focus .menu-item-text, #menu-solutions:ac ...

Update the background image to be smoother, with no text overlay

I am working on a website where I need to smoothly change between background images. Here is the JavaScript code I currently have: var bg=[ 'images/best.jpg', 'images/61182.jpg', 'images/bg.jpg' ...

What is the limitation in transmitting data as a JavaScript object rather than a JSON object?

As a newcomer to expressjs, I recently developed an application using it. Interestingly, when I send data in JSON format through POSTMAN, the application successfully returns the data. However, when I try to send data as a JavaScript object in the request ...

Which method is better for HTML5/JavaScript GeoLocation: Passing data to a callback function or suspending an async call using promises?

Trying to figure out how to utilize HTML5/Javascript Geolocations effectively for passing location data to an ajax call and storing it in a database. The main challenges I'm facing are the asynchronous nature of the Geolocation call and issues with va ...

Retrieving the Selector Value during a Change Event

Is there a way to retrieve the selector value in a change event? I attempted this approach: $("#frek_menonton_tv :input").change(function(){ $(this).selector; }); However, it only returns an empty string. Desired outcome: frek_menonton ...