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

What is the best way to link labels with input fields located separately in Angular?

Imagine a scenario where labels and form fields are being created in a *ngFor loop, as shown below: app.component.ts export class AppComponent { items = ['aaa', 'bbbbbb', 'ccccccccc'] } app.component.html <div class ...

Custom server not required for optional dynamic routes in NextJS version 9.5.2

I am attempting to implement localized routes with an optional first parameter in the form of /lang?/../../, all without requiring a custom server. Starting from NextJS version 9.5, there is a new dynamic optional parameters feature that can be set up by c ...

Ensure history.back() does not trigger Confirm Form Resubmission

Within my web application, every form submission is directed to an action folder. Once the process is complete, the user is redirected back to their original location. However, a problem arises when the user performs an action that requires the application ...

React does not display the items enclosed within the map function

I am facing an issue with rendering elements from a map function. Despite trying to modify the return statement, I have not been able to resolve the issue. class API extends Component { myTop10Artists() { Api.getMyTopArtists(function (err, data) { ...

encounter with file compression using gzip

Currently, I am facing an issue with zipping files using jszip because the backend can only unzip gzip files, not zip files. My front end is built using vue.js. let zip = new jszip(); zip.file(fileToCompress.name, fileToCompress); let component = t ...

Utilizing a foreach loop to control the behavior of two distinct radio buttons as a unified

Can someone help me with a code containing a 5 star rating system (radio button) for two different questions? The issue is that the ratings for each question are linked, so when I make a selection in one question, it clears the selection in the other. It& ...

Use jQuery to assign a value of "true" when a checkbox is

Can you guide me on how to use jQuery to implement a click function that sets the status value to 'true' if a checkbox is checked, and 'false' if it's not checked? If Checkbox 1 is checked, Status 1 should be set to true. Similarl ...

PHP, jQuery, and MySQL combine to create a powerful autocomplete feature for your

I've implemented the source code from into my project, but I'm facing an issue where I can't retrieve any results when typing in the autocomplete textbox. Could someone point out where I might be making a mistake? This is the code I am us ...

Executing MySQL queries synchronously in Node.js

When working with NodeJS and mysql2 to save data in a database, there are times when I need to perform database saves synchronously. An example of this is below: if(rent.client.id === 0){ //Save client connection.query('INSERT INTO clients (n ...

Encountering an Axios Error 404 while attempting to save my information to the MongoDB database

I am encountering an Axios error 404 when trying to register details in a MongoDB database. The error message I am getting is - "Failed to load resource: the server responded with a status of 404 (Not Found)." You can view the Error 404 Image for reference ...

Is it acceptable for Single Page Web Apps to have multiple requests at startup?

I've been dedicated to developing a Single Page Web App (SPA) recently. The frontend is built with BackboneJS/Marionette, while the backend is powered by Java Spring :(. However, I've noticed that the application's start time could be sluggi ...

The white-space property disrupts the normal width of elements

My initial goal was to stack two elements together side-by-side, both taking the full available height. One element has a fixed width of 200px with an image (70px wide) inside, while the other element should only fit one line of text, clipping any overflow ...

Using JQuery functions from other JavaScript files is Simple

When it comes to my CSS, I have taken the approach of creating smaller files for specific functions and then using minification to merge and compress them into one file for easier download. I want to apply the same strategy to my JS Files by logically sep ...

Guide on triggering a modal upon receiving a function response in React

I am looking for a way to trigger a function call within a response so that I can open a modal. Currently, I am utilizing Material UI for the modal functionality. Learn more about Modals here The process involves: Clicking on a button Sending a request ...

Obtaining an XML element within an XSLT transformation

I need to retrieve the value of an XML element within XSL. Although my JavaScript is able to select one XML document, there are elements in other documents that I also require. I am uncertain if this task is feasible or if my syntax is incorrect. This is ...

Upon installation of Next.js, an error in the globals.css file quickly emerged, yet remarkably, it did not disrupt the code in

Here is the link to the repository: here. Once I created the next.js environment using the command "npx create-next-app@latest ./" and ran "npm run dev", I encountered the following error message:- ../../../#React Projects/My projects/causs/styles/global. ...

What is the best way to design a grid with various squares in React Native?

Here's the design I aim to achieve: I am looking to implement the above layout in react native and ensure it is responsive on all screen sizes. I attempted using flexbox but couldn't figure out how to make the boxes square shaped. The code provi ...

Displaying a message text upon successful AJAX request

I have a web page with an AJAX request that updates data in the database. After the update, I want to display a message to the user on the webpage confirming that the data has been successfully updated. However, currently, no message is being displayed and ...

How about a CSS grid featuring squares with square images?

Just like the inquiry found on this page, I am striving to construct a grid of perfect squares, each containing an image with 100% height. The issue arises from utilizing the padding-bottom: 100%; height: 0 method, which prevents height: 100% from functio ...

Utilizing the Bootstrap grid system to dynamically adjust column width based on specific conditions

When working with HTML and bootstrap (3.7) CSS, I often come across this issue: <div class="row"> <div class="col-xs-6">Stretch ME!</div> <div class="col-xs-6">Conditional</div> </div> Sometimes the "Conditional" d ...