What is the best way to apply CSS modifications to sibling elements that are related?

I have several parent div elements with pairs of button and div child elements.

My goal is to apply changes to the corresponding div when a button is clicked. For example, clicking Button 2 should only affect toast 2. However, I am facing an issue where only the first occurrence is being modified regardless of the button clicked.

In the provided example, I demonstrated changing the display value of the relevant element, but any CSS modification should be possible in reality.

You can find a complete and functional codepen here.

function hide() {
  var element = document.querySelector('.toast');
  element.style.display = (element.style.display == 'none') ? 'block' : 'none';
}
.parent {
  position : relative;
  display : inline-block;
  height : 55px;
}

button#button {
  width : 100px;
  height : 35px;
}

.toast {
  display : block;
  position : absolute;
  top : 40px;
  background-color : black;
}
<div class="parent">
  <button id="button" onclick="hide()">Button 1</button>
  <div class="toast">A box with text</div>
</div>
<div class="parent">
  <button id="button" onclick="hide()">Button 2</button>
  <div class="toast">A box with text</div>
</div>
<div class="parent">
  <button id="button" onclick="hide()">Etc...</button>
  <div class="toast">A box with text</div>
</div>

Answer №1

  • Avoid duplicating IDs in your code
  • Consider using addEventListener instead of inline onclick attributes for better code organization
  • Be mindful of the event object passed to your listener to determine the source of the click
  • Utilize methods like closest and querySelector to navigate the DOM effectively

function toggleVisibility(event) {
  if (!event.target.matches(".parent button")) {
    return false;
  }
  const parent = event.target.closest(".parent");
  const toast = parent.querySelector('.toast');
  toast.style.display = (toast.style.display == 'none') ? 'block' : 'none';
}

addEventListener('click', toggleVisibility);
.parent {
  position: relative;
  display: inline-block;
  height: 55px;
}

.parent button {
  width: 100px;
  height: 35px;
}

.toast {
  display: block;
  position: absolute;
  top: 40px;
  background-color: black;
}
<div class="parent">
  <button>Button 1</button>
  <div class="toast">A box with text</div>
</div>
<div class="parent">
  <button>Button 2</button>
  <div class="toast">A box with text</div>
</div>
<div class="parent">
  <button>Etc...</button>
  <div class="toast">A box with text</div>
</div>

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 superior choice for developing a card game: creating it using SVG and the kinetic.js library or utilizing the oCanvas library

When it comes to creating a card game, which platform is more suitable: SVG or canvas using kinetic.js or oCanvas library? In terms of performance, event handling, and object tracking, which option would be more efficient? Additionally, if there is a bet ...

What is the best way to use selenium to extract all p-tags and their corresponding h2-tags?

I am looking to retrieve the title and content from an article: <h2><span>Title1</span></h2> <p>text I want</p> <p>text I want</p> <h2><span>Title2</span></h2> <p>text I want< ...

Why is it necessary to include 'export' when declaring a React component?

When working with React (ES6), there seems to be two variations that I encounter: class Hello extends React.Component { ... } and sometimes it looks like this: export class Hello extends React.Component { ... } I'm curious about the significance o ...

Having difficulty controlling the DOM using cheerio in a Node.js environment

I am currently working on a basic program using Node for the server side with cheerio. Here are the code snippets provided: Server Side: /** * Module dependencies. */ var express = require('express') , routes = require('./routes') ...

convert webpages and images to PDF with a custom watermark

Looking to convert images fetched from the server into PDF format with a watermark by clicking a button. It would be ideal if there is a plugin that allows for PDF preview with disabled user selection and copy options. The website's platform is Sales ...

What steps can I take to resolve the warning about serving images with low resolution in Lighthouse while using Next.js?

I successfully incorporated the svg logo into my webpage using the Next.js Image tag. import Image from "next/Image" export default function Home() { return ( <div> <Image width={32} height={32} src="/logo.svg"> ...

Can you tell me the specific name of the HTML document style that features two columns?

Here are two websites that showcase a unique two-column style layout: http://momentjs.com/docs/ I find these sites visually appealing and I am curious about the specific name of this style. Is there a template or tool available to create documents with a ...

What is the best way to iterate over an array of objects?

I have an Array of Objects that I need to use in order to create an HTML Table: Array(5) 0: Object id: 4 name: Sand Jane address: Green Sand Street ... ... ... 1: Object 2: Object ... ... ... Currently, I am able to perform a search wit ...

How can MessagePorts be effectively utilized in electron Js?

What are some real-world applications of using MessagePorts in Electron JS? Why is it necessary instead of just using ipcRenderer.invoke? I haven't been able to identify any practical scenarios where MessagePorts are indispensable. It seems like it&ap ...

Evaluate the advancement of a test using a promise notification for $httpBackend

I am currently utilizing a file upload feature from https://github.com/danialfarid/angular-file-upload in my project. This library includes a progress method that is triggered when the xhr request receives the progress event. Here is an excerpt from the so ...

Attempting to call setState (or forceUpdate) on a component that has been unmounted is not permissible in React

Hello everyone! I am facing an error message in my application after unmounting the component: Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, canc ...

Switch Between More and Less Text - Implement Smooth Transition on Shopify Using Javascript

I recently implemented a More/Less toggle button using resources from this website. The functionality is there, but I now want to add a smooth transition effect. When the user clicks on "read more," I would like the hidden content to gradually appear, and ...

Unable to use saved images with jQuery Slider

I'm currently facing an issue with adding a jQuery slider to my website. It seems that the slider is not displaying images that are saved on my computer, only images from external websites. Below is the code snippet where I have included an image fil ...

The initial click event for the input element in Jquery is not functioning correctly

I found a jQuery date selector online and the script looked something like this... <script type="text/javascript> $(document).ready(function () { $("#date3").click(function() { $("#date3").scroller({ preset: 'datetime' }); wheels = []; whe ...

Image overlay on a hovering background

I'm currently facing a challenge with creating a hover effect for a background image while keeping the image in front unchanged. I would like the background to darken on hover, but I want the image in front of it to remain the same. Essentially, I ne ...

I keep encountering an error that says "ReferenceError: localStorage is not defined" even though I have already included the "use

I have a unique app/components/organisms/Cookies.tsx modal window component that I integrate into my app/page.tsx. Despite including the 'use client' directive at the beginning of the component, I consistently encounter this error: ReferenceErr ...

The evaluation of jQuery did not function properly on the less.css file

I have a jQuery function that I am using as shown below @winheight:`$(window).height()` within my less file. However, when I compile it to CSS, I encounter a compiler error I am currently using a software called Crunch Compiler Errors You are usin ...

When working with Vuejs, if you try to use "axios" in a .js file, you may encounter an error

I am currently working with VueJS and attempting to send a GET request to my API. I am using axios, but encountering an issue when trying to import it. If I use require for the import, I receive this error: Uncaught ReferenceError: require is not defined. ...

Replace Original Image with Alternate Image if Image Error Occurs Using jQuery (Bootstrap File Input)

I am currently utilizing the Bootstrap File Input component for file uploads, and it's working splendidly. I have set up the initialPreviewConfig to display the existing image on the server. However, there are instances when there is no file available ...

Leverage XMPP with the power of HTML5

I have been intrigued by the integration of xmpp (Extensible Messaging Presence Protocol) with html5 and javascript. How can one implement an xmpp chat in html5? ...