Changing the class of a child element using jQuery's toggle method

I need assistance with a functionality on my website. I have a list of links, and when you click on any of them, it will toggle show/hide text below it in a separate div. Additionally, it hides all other divs if one of them is shown. The code that manages this is as follows:

$(document).ready(function(){
$('.targetDiv').hide();
    $('.hideshow').click(function () {
        $('#div' + $(this).attr('target')).toggle('').siblings('.targetDiv').hide('');
});});

Below is an example of what the link looks like:

<a class="hideshow" target="1"><div class="cennikPlus"><i class="fa fa-plus-square"></i></div>Something something</a>

My goal is to change the class from "fa-plus-square"

to "fa-minus-square"

when open and back to "fa-plus-square" when closed. I have come across the "toggleClass" method which should be useful in this scenario, but I am unsure how to select the i element inside the div within the anchor tag.

Can anyone provide guidance on how to achieve this?

The website where this functionality is needed can be found here

Answer №1

Locate the <i> element and apply toggleClass method

$(this).find("i").toggleClass("fa-plus-square fa-minus-square")

Answer №2

If you want to target the <i> element inside your tag, the code would look like this:

$( this ).find( 'i' )

You have the option to chain commands together to toggle classes like so--

$( this ).find( 'i' ).toggleClass( 'fa-plus-square fa-minus-square' )

When it comes to siblings, if you wish for them all to have the class 'fa-minus-square', use the following code:

$( this ).siblings().find( 'i' ).removeClass( 'fa-plus-square' ).addClass( 'fa-minus-square' )

Answer №3

Utilizing parent-child selectors in jQuery is a straightforward process...

$("a > div > i")

This code snippet will target the i element that is nested within a div, which is itself nested within an a element. For more information, click here.

If the elements are not immediate children, you can simply remove the greater than sign as seen below.

$("a div i")

Answer №4

Well, here goes nothing... I decided to venture into the world of combining jQuery code with existing code for the first time. I tried something out, and it didn't quite work as expected. I initially thought that I had made a mistake somewhere, but it turned out that the actual issue was my selection of the "li" element instead of the "i" element. The solution came to me when I added this line just before the final line:

$(this).children('div').children('i').toggleClass("fa-plus-square fa-minus-square");

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

Obtain the background color of an element using the source attribute in Selenium WebDriver

Understanding the x-path is crucial, such as < img id="" src="/A/A/B.png" style=""> My task involves identifying the color of the image, but unfortunately, the style attribute does not provide any information about color. It only includes details a ...

What is the best way to extract individual words from a string based on a specified list of tokens?

I am currently working with a list of tokens used to create artificial Japanese words, which is represented by the following array: var syllables = ["chi","tsu","shi","ka","ki","ku","ke","ko","ta","te","to","sa","su","se","so","na","ni","nu","ne","no","ha ...

Enhance the volume of an item within an array using JavaScript, React, and RecoilJS

When I check the console, the result is correct. However, when I try to replace that array in setCart, it doesn't work. This is using RecoilJS. const cartState=[ { id:1, productName:'Apple',price:100,quantity:1}, { id:2, productName: ...

What are the steps for integrating Landbot into a Next.js application?

I've been attempting to integrate Landbot into my Next.js application, but I'm facing some difficulties. I tried to modify the _document.js file and insert the necessary code into the body section, however, it doesn't seem to have any impact ...

Steps for designing a footer with a fixed width and transparent center gap that stays in place

Looking to create a fixed footer with a transparent gap at the center that is 100% fixed width? No scripts needed! EXPAND THIS WAY <<< ______ FIXED WIDTH GAP ______ >>> EXPAND THIS WAY MY OWN SOLUTION HTML <div id="Ftr"> ...

Ways to perfectly align objects in a container without compromising the height of the parent element

Within my container div, I have two spans. An issue arises when I attempt to align the items to the center using align-items: center, as this causes the spans to lose their defined height and border-radius properties. My goal is to keep the heights and bor ...

Interface-derived properties

One of the challenges I'm facing is dealing with a time interval encapsulation interface in TypeScript: export interface TimeBased { start_time: Date; end_time: Date; duration_in_hours: number; } To implement this interface, I've created ...

Create a unique filter in an ng-repeat directive that allows users to personalize the data displayed

Is there a way to create a custom filter that hides the inventory column for Color Pencil Special on October 2nd, 2017 in the view? The inventory for Color Pencil Special is dependent on the inventory of regular Color Pencils, which are stored somewhere e ...

Retrieve the property of an object from within an array

I am dealing with an array structure like this: const arr = [{ name: 'One', id: 1 }, { name: 'Two', id: 2 } ]; My goal is to extract and return the name of the object if its id matches a certain value. After exp ...

Is it possible to eliminate certain JavaScript code by clicking on something?

I've been searching for a solution to this issue without any luck. Currently, I have two main JavaScript functions running on a website I'm developing. One is for lazy loading images and the other is for smooth scrolling to an anchor link at the ...

Scrolling the bottom of a PDF object element in HTML using JavaScript - a simple tutorial

There is a Pdf object displayed on my website <object data="data/test.pdf" type="application/pdf" width="700" height="900"> </object> I'm trying to automatically scroll this pdf to the last page when the page loads. I've found tha ...

Failure to give an error message occurred during a POST request on Parse.com and ExpressJS platform

I'm facing an issue where a POST request I send fails with error code 500 and there is nothing showing up in my server side error log. It seems like the cloud method may be missing. What's interesting is that the same POST request works fine wit ...

Is it advisable to utilize both bootstrap.css and normalize.css simultaneously?

Is it redundant to use both bootstrap.css and normalize.css since bootstrap already includes a version of the code from normalize.css? In order to ensure thorough cross-browser compatibility, should I use both bootstrap and normalize.css, or is using just ...

How to eliminate file extensions with grunt-contrib-connect and grunt-connect-rewrite

I'm struggling to find a solution for eliminating the '.html' extension from files within my grunt web app. should display index.html from the respective folder. However, in the absence of a trailing slash (), the page should instead look ...

determining if two words are synonymous or not

For this task, you are required to develop a program that can determine if two words are synonymous. A synonym dictionary will be provided with pairs of corresponding words. Your program will then need to respond to queries regarding whether two given word ...

Using jQuery to eliminate the 'disabled' attribute from CSS

After using the .val() method to enter data into a text box, I noticed that when trying to click "add", the button appears disabled. <input class="btn-primary action-submit" type="submit" value="Add" disabled=""> If I manually type in text, the dis ...

What is the best way to activate an alert or swal function just once instead of repeatedly?

I am just starting to learn Angular. Currently, I have an application that contains two variables related to the status of financial transactions. These variables are: tab1TrxMessage, which holds any important messages, and tab1TrxStatus that indicates wh ...

Maintaining a Multi-page template in PhoneGap: Best practices

I'm a beginner in Hybrid app development, currently using PhoneGap and Jquery Mobile. In my app, I have around 10 separate pages such as login.html, index.html, search.html, etc. My query is whether I should include all JS and CSS files on each indivi ...

Tips for Formatting Mandatory Message Input Fields and Text Boxes

I am in the process of creating a contact page for my Reactjs website, but I am unsure how to style the required message that should appear below the input or textarea upon clicking Submit. Can anyone guide me on how to achieve this? Relevant Code <for ...

What exactly is the function of passport.authenticate when it is called on a callback

I have integrated passport js into my express project. The initial route presented below is responsible for creating the user in my database and subsequently redirecting to the second callback route. What does the function 'passport.authenticate(&apo ...