switching the CSS class of a different child element from its parent

Having just started working with jQuery, I'm struggling to figure out how to target specific elements when clicking on toggle buttons.

My goal is to toggle the class of each respective text container (from collapsed to expanded) when its corresponding toggle button is clicked. However, regardless of which toggle button I click on, all text containers seem to be affected.

Here is my current JavaScript code:

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

        $(".textContainerCollapsed").toggleClass("textContainerExpanded", 500);

        // Other methods I've tried:
        // $(this).parent(".textContainerCollapsed").toggleClass("textContainerExpanded", 500);
        // $(this).parent.children(".textContainerCollapsed").toggleClass("textContainerExpanded", 500);
        // $(this).parent.next(".textContainerCollapsed").toggleClass("textContainerExpanded", 500);
        // $(this).parent(".parent").next(".textContainerCollapsed").toggleClass("textContainerExpanded", 500);
        // $(this).parent(".parent").children(".textContainerCollapsed").toggleClass("textContainerExpanded", 500);
        // $(this).parent(".parent").find(".textContainerCollapsed").toggleClass("textContainerExpanded", 500);
        
    });
});

And here is a snippet of my HTML markup:

<div class="parent">
    <div class="buttonContainer">
        <a href="#" class="toggleButton">Toggle</a>
    </div>
    <div class="textContainerCollapsed">
        Some text
    </div>
</div>
<div class="parent">
    <div class="buttonContainer">
        <a href="#" class="toggleButton">Toggle</a>
    </div>
    <div class="textContainerCollapsed">
        Some text
    </div>
</div>

Lastly, here is the relevant CSS:

.textContainerCollapsed
{
    height: 0px;
    overflow: hidden;
}
.textContainerExpanded
{
    height: 100%;
    overflow: hidden;
}

Answer №1

Here are three different versions for expanding a text container:

$(this)
  .closest(".parent")
  .find(".textContainerCollapsed")
  .toogleClass("textContainerExpanded");

Another way to achieve the same result is by using:

$(this)
  .parent()
  .next()
  .toogleClass("textContainerExpanded");

Alternatively, you can also expand the text container with:

$(this)
  .parent()
  .siblings()
  .toogleClass("textContainerExpanded");

Answer №2

$('.toggleBtn').on('click', function() {
    $(this).parent().next()
           .toggleClass('textCollapsed textExpanded');
});

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

Ways to implement jQuery for tables in a Ruby on Rails environment

I am a beginner in web app development with RoR and I could use some assistance with jQuery. On my webpage, I have a table displaying messages along with two moderation buttons - Accept and Decline message. .../view/messages/index.html.erb <div class ...

Adding a class using jQuery based on whether a section is visible or hidden on the screen

Seeking advice on the best approach to take. Division 1 or section - Apply style 1 if division 1 is currently visible on the screen. Division 2 or section - Apply style 1 if division 2 is currently visible on the screen. Division 3 or section - Apply st ...

Do AJAX requests hinder performance and how long do they typically last?

Even though I have experience in web development, I still find myself feeling a bit uneasy asking these basic questions. However, I believe it's always good to verify my assumptions... In my application, I am working on recording unique image views. ...

Using d3 to create an SVG with a Bootstrap dropdown feature

I am seeking to create a graph that is not a tree, as some nodes may have multiple parents. When a node on the graph is clicked, a dropdown menu should be displayed with a list of text options. Though I am new to d3.js, I have observed examples of bootstra ...

Alter the background of a div in a webpage using PHP and jQuery to display a

I have a collection of 10 background images for each season (Spring, Summer, etc.) stored in folders labeled 1, 2, 3, and 4. I am looking to randomly change the div background image for each season. For example, changing the random image from folder 1 for ...

Is it feasible to access the PHP code of a website?

Is it within the realm of possibility to access and view the PHP files and codes of other websites? In other words, can individuals without access to the files see my PHP codes? If this is a concern, what is the most effective way to safeguard against it ...

Assigning websockets to a global variable may cause them to malfunction

I'm utilizing websockets in conjunction with JavaScript and HTML5. Here is the code snippet I am currently working with: <input type="text" onFocus="so = new Websocket('ws://localhost:1234');" onBlur="so.close();" onKeyUp="keyup();"> ...

Positioning Backgrounds with Padding in DIV Elements

I am trying to figure out how to add a check mark next to text in a button with specific styling. I have managed to get the check mark aligned properly using Background:left center, but I also want to add padding and adjust spacing. Is there a way to achie ...

Is my Bootstrap malfunctioning? The grid system seems to be malfunctioning

My very first question here is quite simple. I have a script that creates rows with dynamic content by appending 4 boxes (columns) in one row and then appending the row to the container. After completing this process, it appends the container to the main c ...

Utilize Bootstrap's form-inline feature to arrange fields side by side in one neat

I am looking to customize my sign-in form layout by displaying the fields in a row next to each other rather than under each other. header: Update: I have successfully implemented this code <header class="navbar navbar-fixed-top navbar-inverse"> & ...

Utilizing conditional styling in React: the ability to add or attach CSS classes based on

Is there a more efficient way to implement conditional formatting for this scenario? const PaginationStorePageLink = ({ store, pageNum }) => (observer(({ PaginationStore }) => { const className = this.props.store.currentPage === this.props.pageNum ...

Unable to retrieve post data during AJAX insertion in CodeIgniter

I am using ajax to send data to my Codeigniter controller from an external JS file. Below is the ajax code snippet I am using: $.ajax({ url: 'http://localhost/test/testController/testFunction/', ...

organizing the div based on the given data

I'm working on developing a web application using HTML and AngularJS. There are two main div elements: Div 1 <div class="box1" style="margin-top:20px;"> <span ng-repeat="i in data" style="font-size:14px; font-weight:normal">{{i.div ...

The filter search feature fails to return any results when data is inputted into the tables

I have implemented a filter search feature within two tables on my website. My goal is to retrieve the search results for a specific drink while keeping the table headings fixed in their positions. For instance, if I type "Corona" into the search box, I ...

Is it possible to set the input form to be read-only?

I need to create a "read-only" version of all my forms which contain multiple <input type="text"> fields. Instead of recoding each field individually, I'm looking for a more efficient solution. A suggestion was made to use the following: <xs ...

Tips for minimizing the arrow size in the infowindow on a Google Maps interface

As a newcomer to customizing Google Maps, I am looking to decrease the size of the arrow in the infowindow and position it in the bottom left corner for a better appearance. I am struggling to figure out how to adjust the height and width of the arrow and ...

The HTML file seems to be having trouble connecting to the JavaScript file

I am currently working on a small, fun website project and have an HTML file along with a JavaScript file in the same directory. However, my HTML seems to be unaware of the existence of my JavaScript file. It fails to execute the function during the load e ...

Issue with Bootstrap flash alert CSS on mobile devices is not functioning properly

I am in the process of developing a Rails application. Within my app, I utilize Bootstrap's CSS for displaying flash messages on alerts. Instead of fully incorporating Bootstrap's CSS, I only integrate styles related to alerts in order to prevent ...

Learn the method for toggling images in HTML while simultaneously storing a 0 or 1 in a flag variable

In my design, I would like to have a star icon that displays two star icons at once - one blank and the other yellow. These stars will swap their appearance when clicked or tapped on touch screen devices. Additionally, I want to be able to store values as ...

Ways to implement the tabIndex attribute in JSX

As per the guidelines provided in the react documentation, this code snippet is expected to function properly. <div tabIndex="0"></div> However, upon testing it myself, I encountered an issue where the input was not working as intended and ...