Hide only the table that is being clicked on, not all tables

Essentially, I am using document.querySelectorAll() to retrieve an array of div elements. In my function, handleClick(), each time the button is clicked, I want to hide the table associated with that specific button.

This is the current situation: https://i.sstatic.net/gJLM6.png

When I click one of the dropdown buttons, this is what occurs: https://i.sstatic.net/bVfAL.png

CURRENT BEHAVIOR: All tables are hidden

EXPECTED BEHAVIOR: Only the table related to the clicked button should be hidden

Below is a snippet of the code from the file:

const handleTitleClick = (e) => {
    const row = document.querySelectorAll(
      "div[class*='MuiDataGrid-root']"
    ) as NodeList;

    const rowArr = Array.from(row);

    rowArr.map((r, i) => {
      const somerow = r;
      somerow.style.display = 'none';
      return row;
    });

    console.log(e);
    console.log(rowArr);
    console.log(row);
  };
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Answer №1

To hide specific tables, you don't need to apply display: none to every table on the page. Instead, you can target individual tables associated with a hide button by wrapping them in additional divs. Here's an example:

return (
<div>
  <button
    onClick={() => {
      const table = document.querySelector("#table-wrapper-1");
      table.style.display = "none";
    }}
  >
    Hide table1
  </button>
  <div id="table-wrapper-1">
    <MyTable1 />
  </div>
  <button
    onClick={() => {
      const table = document.querySelector("#table-wrapper-2");
      table.style.display = "none";
    }}
  >
    Hide table2
  </button>
  <div id="table-wrapper-2">
    <MyTable2 />
  </div>
</div>;

)

Additionally, for better practice, I suggest using refs instead of querySelector.

Answer №2

// Select all elements with the class "allBtn"
const allButtons = document.querySelector(".allBtn");

// Add click event to each button
allButtons.map((button, index) => {
   button.addEventListener("click", () => {
     // Add data attribute to the HTML and create a table with the same ID as the button's data attribute
     let currentId = button.getAttribute('data-attr');
     // Get the table corresponding to the current button
     let currentTable = document.getElementById(`${currentId}`);
     currentTable.style.display = 'none';
   });
})

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

Review the Drawer Item's Render Method

I have been using react-native with expo and following a specific guide closely: Is there an alternative way to implement this without the use of icons at the moment? Upon compiling, I encountered an error regarding the Render Method of DrawerItem. I&apo ...

Looking for a resolution with NicEditor - Seeking advice on incorporating custom select options

I recently started using NICInline Editor and found a helpful sample at Is there a way to incorporate custom options into this editor? I would like the selected option's value to be inserted right at the cursor point of the Editor Instance. Query: H ...

Transforming a React Class Component into a React Functional Component

After struggling for a day with multiple failed attempts, I have been unsuccessful in converting a React Class Component. The original class component code is as follows: class NeonCursor extends React.Component { constructor(props) { super(props); ...

Nest a Div inside another Div with a precise margin of 10 pixels

Recently, I attempted to create a fullscreen webpage like this one: https://i.sstatic.net/21KCr.png My goal was to have the color of each element change randomly every second. Here is the JavaScript code I implemented: <script> var tid = se ...

Sorry, I am unable to fulfill this request as it involves rewriting copyrighted content. However, I can provide some

Whenever I attempt to execute create-react-app myapp, I keep encountering an error. I have also attempted to clear the cache using npm cache clean --force Unfortunately, this did not resolve the issue. internal/modules/cjs/loader.js:638 throw err; ^ Er ...

selecting a div element with a label using the nth-child property

I recently discovered the CSS3 :nth-child() Selector and decided to create a sample Here is the HTML snippet: <body> <div> <label>dsdf</label></div> <div>seconddiv</div> </body> And here's the CSS par ...

ES6 - Error of duplicate declaration when importing files

Before ES6: var stream = require("./models/stream"); var stream = require("./routes/stream"); The above code works without any issues. With ES6: import stream from './models/stream'; import stream from './routes/stream'; But now, a ...

Struggling to implement a vertical scroll bar in HTML code?

<body ng-app="myApp" ng-controller="myCtrl"> <div ng-show = "dataFromRest" ng-repeat = "x in dataFromRest.posts" > <div class="tittle" style="width: 25%;"> <a href="" ng-click="showDi ...

Create a full-page gradient background using CSS that spans the entire height of the

I need assistance with a website that features a gradient implemented through CSS like this: #grad { background: -webkit-linear-gradient(#87a0b4 80%, #6b88a1); background: -o-linear-gradient(#87a0b4 80%, #6b88a1); background: -moz-linear-gradi ...

Using querySelector to Target Elements by their InnerHTML Content

Is it possible to target an element by its innerHTML directly without the use of loops? Is there a way to achieve this with something like document.querySelector('div[innerHTML="Sometext"]') or document.querySelector('div[textcontent="Som ...

Modernized Style - Additional Scrolling Feature for List Element

I've implemented code from Google's Material Design website for my project: https://material.io/components/web/catalog/lists/ Although it works well, the issue arises when more list entries are added and I have to scroll down to view them. The p ...

Using Input Mask with TextField Component in Material-UI with React Hook Form

Currently, I am trying to utilize the MUI's TextInput component alongside the MaskInput component from react-input-mask and react-hook-form. Despite everything appearing to be functioning correctly, an error message related to using refs keeps popping ...

Sleek dialog sliding animation with Svelte

I'm struggling with a svelte component that I have and I'm trying to implement a slide down animation when it closes. The slide up animation is functioning correctly, but for some reason the slide down animation is not working. Does anyone have a ...

Having difficulty accessing and updating data in a database while using Discord.js

My goal is to enable staff to respond to the last direct message (DM) by using ~reply <message> instead of ~dm <userID> <message>. However, before I can do that, I need to store the user's ID in a database to identify the last person ...

Proper method for adding elements in d3.js

I have a block of code that selects an #id and appends a svg-element into it: var graph = d3.select(elemId).append("svg") .attr('width', '100%') .attr('height', '100%') .append('g') Within th ...

Utilizing JQuery to make Google listings easily findable

Implementing Google Places for a location text box has been successful. However, I am now looking to create a class-based implementation so that I can use it with multiple places effortlessly. Is it possible to achieve this using JQuery? <script type ...

Adjusting the position of just a single box in a flexible layout

I have multiple columns set up in a similar way. <div style="display: flex;flex-direction:column"> <main class="main-contents" role="main">TopHeader </main> <div> content A</div> <div> conte ...

Invoke jQuery within a nested context once more in the jQuery method sequence

Is it possible to do something like this? jQuery(selector).jQuery(subselector).command(....) Here is the current code snippet: $(' .species') .filter(function () { return !$(this).data('hidden_code_ready'); } .wrapInner('<spa ...

Running npm commands, such as create-react-app, without an internet connection can be a

Currently, I am working in an offline environment without access to the internet. My system has node JS installed. However, whenever I attempt to execute the npm create-react-app command, I encounter an error. Is there a workaround that would allow me to ...

"The issue of Django showing a 'select a valid choice' error when trying to populate a select field

I encountered a validation error while trying to create a form with an empty select field: area_sp = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-control', 'id':'area_select'})) After populating the ...