"What is the most efficient method to display or hide multiple divs using

Hey, I'm trying to figure out how to work with showing or hiding multiple div elements quickly. Do I really need to number each div like "open,close,show_text"? It seems a bit repetitive if I have to do it for each div 10 times.

Open 1
Open 2

Answer №1

Enclose your content within a container div, and then you can utilize

  1. .closest()

Retrieve the closest ancestor of each element in the set that matches a specific selector, traversing up through its ancestors in the DOM tree.

  1. .find()

Find the descendants of each matched element by filtering with a selector, jQuery object, or an element.

HTML

<div class="container">
    <div class="open" style="cursor:pointer">Open 1
    </div>
    <!-- open -->
    <div class="close" style="cursor:pointer; display:none;">Close 1
    </div>
    <!-- close -->
    <div class="show_text" style="display:none;">
    hello world 1
    </div>
</div>

Code

$(".open").click(function() {
    //Locate the nearest container div
    var container = $(this).closest('.container'); 

    //Use .find() to pinpoint child elements
});

Check out this example:

$(document).ready(function() {
  $(".open").click(function() {
    var continer = $(this).closest('.container');
    continer.find(".show_text").show('blind');
    continer.find(".open").hide();
    continer.find(".close").show();
  });
  $(".close").click(function() {
    var continer = $(this).closest('.container');
    continer.find(".open").show();
    continer.find(".show_text").hide('blind');
    continer.find(".close").hide();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">
  <div class="open" style="cursor:pointer">Open 1
  </div>
  <!-- open -->
  <div class="close" style="cursor:pointer; display:none;">Close 1
  </div>
  <!-- close -->
  <div class="show_text" style="display:none;">
    hello world 1
  </div>
</div>
<!-- show_text -->
<div class="container">
  <div class="open" style="cursor:pointer">Open 2
  </div>
  <!-- open -->
  <div class="close" style="cursor:pointer; display:none;">Close 2
  </div>
  <!-- close -->
  <div class="show_text" style="display:none;">
    hello world 2
  </div>
</div>
<!-- show_text -->

Answer №2

$(document).ready(function(){
    $("div[class^=open]").click(function(){
        $("div[class^=show_text]").show('blind');
$("div[class^=open]").hide();
$("div[class^=close]").show();
    });
    $("div[class^=close]").click(function(){
        $("div[class^=open]").show();
$("div[class^=show_text]").hide('blind');
$("div[class^=close]").hide();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="open" style="cursor:pointer">Open 1
</div><!-- open -->
<div class="close" style="cursor:pointer; display:none;">Close 1
</div><!-- close -->
<div class="show_text" style="display:none;">
hello world 1
</div><!-- show_text -->

<div class="open2" style="cursor:pointer">Open 2
</div><!-- open -->
<div class="close2" style="cursor:pointer; display:none;">Close 2
</div><!-- close -->
<div class="show_text2" style="display:none;">
hello world 2
</div><!-- show_text -->

Answer №3

After analyzing the information you've provided, I see an opportunity for improvement. If you're still searching for a solution, consider utilizing a loop to enhance efficiency in completing the task at hand swiftly. Opting for jQuery's show() and hide() functions may hinder your progress rather than facilitating it.

In order to assign numbers to each element and display them dynamically based on specific conditions, consider delving into JSON, JavaScript's sophisticated and distinguished counterpart. Should you require further guidance, feel free to reach out. Otherwise, best wishes.

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

Making a post request with Ajax in Node.js

Dealing with an issue in Node js and AJAX POST - the Node request fails to verify if the form data is being handled correctly, consistently triggering the error function. Is there any solution to check the AJAX NODE JS CODE below? $("#submit_btn").click ...

Pagination - crafting a fresh page

Seeking advice on the best practice for client-side handling of pagination in a question/answer thread, similar to Stack Overflow. The data structure includes upvote/downvote comments and looks like this: data: (10) [{…}, {…}, {…}, {…}, {…}, { ...

Implementing a progress bar in Rails 4 to delete a remote file using Fog and waiting for controller respond_to

I've been searching for solutions to implement a progress bar in my Rails 4 application. I have a scenario where users can delete images associated with a record, and the images div is updated via jQuery after deletion. However, since the deletion pro ...

Tips for halting a MySQL database transaction within a NodeJS environment using expressJS

Recently, I encountered a coding challenge that involved managing a long database transaction initiated by a user. The scenario was such that the user inadvertently updated 20 million entries instead of the intended 2 million, causing a significant impact ...

Bootstrap image with simplistic arrow indicators

I'm facing a minor issue that I need help solving. I want to have two simple arrows (one pointing left and one right) vertically aligned in the center of an image. Additionally, these arrows should resize proportionally when the screen size changes. ...

Troubleshooting a CORS problem with connecting an Angular application to a Node server that is accessing the Spotify

I am currently working on setting up an authentication flow using the Spotify API. In this setup, my Angular application is making calls to my Node server which is running on localhost:3000. export class SpotifyService { private apiRoot = 'http://lo ...

My React/Redux App is experiencing difficulties as the state fails to load

Currently, I am working on a project based on the Redux Documentation page. Instead of uploading it directly to Stack Overflow, I decided to share my progress on GitHub: https://github.com/davidreke/reduxDocumentationProject I have completed the instructi ...

the php renderer fails to take into account the styles

Trying to convey this as clearly as possible. I have the variables below: $name = main channel and $childs = sub channels. When I remove the childs from the HTML, only the main channel shows up - which is expected. However, when attempting to style the su ...

Transforming a pandas dataframe into an interactive HTML table, emphasizing particular data points

I need help with converting pandas data frames to HTML and highlighting specific elements. My task involves creating two pandas dataframes, rendering them to HTML, and comparing their elements: import pandas as pd import webbrowser data1 = [1, 2, 3, 4, ...

Explore how to effectively use multiple values in a jQuery filter function when working with data attributes

Exploring the use of jQuery filter for data attributes with tables that contain team, specialization, and level data variables. Seeking advice on the best approach and typical usage methods. Here is my HTML code: <table data-team="<?php print $name[ ...

The X-frame-Options HTTP response header is ineffective

I've been attempting to implement the X-Frame-Options response header in my application by configuring it on my express server. Utilizing the helmet npm package, I've applied the following code snippet: const express = require("express" ...

Create custom components by wrapping npm components and exporting them as a single custom component

Encountering issues while installing 3rd party components from npm. For instance, a dropdown react module that can be used easily in my own module; however, I find myself needing to declare its style and other dependencies in multiple modules. For example ...

Generate a JSON object based on the request.body information

Currently using NodeJs along with Express for building a REST API. The functionality is all set up and running smoothly, but I'm facing an issue in comprehending how to iterate through the request.body object and validate its fields for any undefined ...

Display the table upon completion of the form submission

I am trying to create a form where the table #mytable is only displayed after the form has been submitted. If nothing is entered in the form, the table should remain hidden. Any suggestions on how I can achieve this? <form action="" id="myform" method ...

The CSS font-weight attribute can be set to bold or light

I've encountered a strange issue with the font-weight property when applied to a button element. When set to 400, everything functions as expected. However, attempting to set it to either 300 or 500 does not produce any noticeable changes. Interesting ...

How can you temporarily delay the original ajax request until a certain condition is satisfied before proceeding?

I'm looking to set up a recaptcha process that intercepts all ajax requests before they are executed - here's how I envision the process unfolding: A user performs an action that triggers an ajax request. If the user has already completed the r ...

What is the best approach for implementing component composition in AngularJS that resembles the render props pattern seen in React?

I'm currently working on developing a grid component in AngularJS that dynamically populates its grid items at runtime, similar to the render props pattern in React. My goal is to achieve this by utilizing the latest AngularJS components API along wi ...

Repeated Hover Effects on CSS Menu Icons

the webpage I need help with is (issue with general menu drop down) Hello I recently decided to enhance my menu by incorporating icons. I had successfully implemented a drop-down menu using only HTML and CSS, but when I attempted to add icons next to ea ...

Having trouble with the scrollTop function in your Rails application?

I recently delved into using jQuery and have implemented a two-column layout with Twitter Bootstrap. The CSS in my file looks like this: html, body { overflow: hidden; height: 100%; } .span8, .span4 { overflow: auto; } This setup results ...

How come my function does not properly update the visibility of the elements with each subsequent call?

I am currently implementing form validation and updating the display of a notification based on the status code received from an http request with the following code: function checkValidEndpoint() { var xmlHttp = null; var myurl = "/restyendpoint/ ...