What is the best way to switch a single class using jQuery without impacting other elements with the same class

I'm in the process of implementing a commenting system similar to Reddit on my website. Each comment is equipped with a small button in the top right corner that allows users to collapse the comment.

To achieve the collapsing effect, I am utilizing jQuery toggleClass.

$(".button").click(function() {

  $('.bottomtext').toggleClass('bottomtext-small');
  $('.upvote').toggleClass('upvote-small');
  $('.downvote').toggleClass('downvote-small');
  $('.main-content').toggleClass('main-content-small');
  $('.button').toggleClass('button-small');

});

While the comment collapsing feature functions correctly on individual comments, toggling the class results in every comment collapsing. How can I ensure that only the comment associated with the clicked button is affected?

For a demonstration, view the JSFiddle: https://jsfiddle.net/j765rkpc/7/

Answer №1

If you're looking to target specific elements with certain class names within the same post as the button that was clicked, you can achieve that with the following code snippet:

$(".button").click(function() {
  const $post = $(this).closest('.post-container');
  $post.find('.bottomtext').toggleClass('bottomtext-small');
  $post.find('.upvote').toggleClass('upvote-small');
  $post.find('.downvote').toggleClass('downvote-small');
  $post.find('.main-content').toggleClass('main-content-small');
  $post.find('.button').toggleClass('button-small');
});
.post-container {
  background-color: yellow;
  margin: auto;
  position: relative;
  display: flex;
  width: 75%;
  max-width: 1440px;
}

/* CSS styles for various elements within the post container */
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="post-container">
  <div class="left-side">
    <div> <img class="upvote" src="https://i.imgur.com/AdwzPRs.png" height="15"> </div>
    <div> <img class="downvote" src="https://i.imgur.com/XoJ1Jjy.png" height="15"> </div>
  </div>
  <div class="post">
    <p class="toptext">
      <input type="button" class="button"></input>
      <span class="username">webdev18</span>&nbsp;&nbsp;&nbsp;&nbsp;33 points&nbsp;&nbsp;18 minutes ago
    </p>
    <div class="main-content">
      <p class="contain-com">
        When I want to collapse this comment by clicking the button in the corner...
      </p>
      <p class="bottomtext">
        <img src="https://i.imgur.com/1IIJe1r.png" height="15">Respond
      </p>
    </div>
  </div>
</div>
<!-- Additional post containers with similar structure for demonstration purposes -->

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 method for centering text input within an Angular Material toolbar?

Can anyone help me with aligning input elements with buttons on an Angular Material toolbar? Check out the code pen: http://codepen.io/curtwagner1984/pen/amgdXj Here is the HTML code: <md-toolbar class="md-hue-1" layout-align="start center" style="mi ...

Is the tabindex feature malfunctioning for the submit button in an HTML form?

Hey there, I created the design like this. However, the submit Tabindex is not working as expected. Can you please take a look at it and let me know what might be causing this issue? <input id="id" type="text" value="" class="input" tabindex="1"/> ...

In Vue, you can dynamically load a JavaScript file containing a JavaScript object during runtime

I'm in the process of developing a no-code application with Vue. I have come across an issue where I cannot add functions to a JSON file that I want to import at runtime. As a workaround, I decided to use a JavaScript or TypeScript file to store the J ...

An issue arises when attempting to utilize the 'push()' method to append a string to a JSON array

I am looking to append strings to my JSON file structure shown below: { "items": [] } To achieve this, I have the requirement of using the following code: var items = require("../../config/item.json"); The approach I am taking is ...

Using jQuery to make a PNG image draggable and allow it to overlap with

Can jQuery's Draggable be used with an overlapping PNG image (not as a background image, but for printing purposes)? I attempted using the CSS style "pointer-events: none," however this solution does not function correctly in Internet Explorer. <d ...

The assigned type does not match the type 'IntrinsicAttributes & { children?: ReactNode; }'. This property is not assignable

I have been struggling to resolve this issue, but unfortunately, I have not found a successful solution yet. The error message I am encountering is: Type '{ mailData: mailSendProps; }' is causing an issue as it is not compatible with type &apos ...

Issue with Angular 2 (Ionic 2): Struggling to properly display Component within Page

I have successfully created an Angular 2 Component: import {Component, View} from 'angular2/core'; @Component({ selector: 'sidemenu' }) @View({ templateUrl: 'build/pages/menu/menu.html', }) export class Menu { } Howev ...

Vue.js is displaying one less item

Recently I started working with Vuejs and encountered an unexpected issue in my application. The purpose of my app is to search for channels using the YouTube API and then display those channels in a list. However, when I try to render the list of subscri ...

Steps to obtain the precise source code of a webpage

Is there a way to download the exact source code of a webpage? I have tried using the URL method and Jsoup method, but I am not getting the precise data as seen in the actual source code. For example: <input type="image" name="ctl00$dtlAlbums$ct ...

How can you display or conceal an HTML page in Jquery Mobile?

This code snippet is used for toggling the visibility of a div. $("[id*=viewMeButton]").click(function(){ $("[id*=viewMe]").toggle(); $("[id*=viewMeButton]").show(); }); In Jquery Mobile, similar functionality can be implemented to show/hide a ...

The gltf model fails to load on Chrome for Android when using Threejs

I encountered an issue while attempting to showcase a basic GLTF 3d model on my website. Surprisingly, it functions smoothly on desktop Mac and Windows, as well as on iOS in Safari and Firefox. However, it fails to load on Android's Chrome browser. St ...

Is it possible to update a MobX state when a message is received from Firebase in the background?

I've set up Firebase in my project like this: import { initializeApp } from 'firebase/app'; import { getMessaging, getToken, onMessage, isSupported } from 'firebase/messaging'; import store from './flag'; ...

generate a customized synopsis for users without storing any data in the database

In order to provide a summary of the user's choices without saving them to the database, I want to display it in a modal that has already been created. Despite finding some sources online, none of them have worked for me so far. Below is my HTML: &l ...

Display a list next to a block of text and image using HTML and CSS styling

I am having trouble with keeping a navigation list aligned inline with a block of text that includes an image. My issue arises when I expand the browser to full screen size, causing the list to overlap the text block. Here is the HTML code snippet: <bo ...

JavaScript and jQuery are lightning fast, especially when the page is reloaded

I am currently working on a responsive website that uses liquid layouts. I have encountered challenges when incorporating images in the design, especially when dealing with different browsers like IE, Firefox, and Chrome. Recently, I faced another issue w ...

What is the process of displaying JSON headers using JavaScript?

Although it may seem like a simple question, I am new to JSON. Can someone explain how to display a heading in the console? This is the code I have: var jsonstr = '{"profile":{"name" : "raj","age":"35&qu ...

What is the best way to transfer a JavaScript object with string values containing quotes from node.js to the browser?

I have a node/express application and need to send a JavaScript object to the browser. Currently, I achieve this by using JSON.stringify on the object and then embedding it into the HTML: In my Node.js/Express code: var myObject = /* fetched from databas ...

Trouble with Ajax program loading properly in Chrome browser

I have developed a small ajax program and encountered an issue. While it works perfectly fine on Internet Explorer 11, it does not function correctly on Chrome and Firefox. Here is the HTML file snippet: <html> <head><title>Ajax Page< ...

A guide on organizing an array of objects by a specific property using a separate array

Here is the array I am working with: var arr = [ { count: 27, dataRil: "08/06/21", subCateg: "FISH", }, { count: 22, dataRil: "08/06/21", subCateg: "DOG", }, { count: 28, dat ...

Getting a variable from an ajax call and using it in a Pug template

Currently, I am experimenting with Express and Pug to learn some new concepts. Upon making a request to a website, I received some dynamic information stored in an array. However, I am facing challenges when trying to iterate over this array using Pug. The ...