If a div contains the class "active", then modify the background color of another div

One thing I want to achieve is changing the background color of a div element with the class .panel-heading to blue if the inner div element with the class .panel-collapse inside the parent div with the class .panel has a class of in. The framework I am using for this functionality is Bootstrap accordion.

This is an example snippet of my HTML code:

<div class="panel panel-default">
    <div class="panel-heading">
        <h4 class="panel-title">
            <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
                Lipsum set dolor
                <span class="pull-right glyphicon glyphicon-minus"></span>
            </a>
        </h4>
    </div>
    <div id="collapseOne" class="panel-collapse collapse in">
        <div class="panel-body">
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since
        </div>
    </div>
</div><!-- end panel -->

I attempted a simple solution like this, however it did not produce the desired effect:

if ($('.panel-collapse').hasClass('in')) {
    $(this).closest('.panel-heading').css("background", "blue");
}
else {
    $(this).closest('.panel-heading').css("background", "red");
}

Answer №1

.panel-heading is a sibling of .panel-collapse. You can try the following approach using the siblings() method.

$('.in').siblings('.panel-heading').css("background", "blue");

$('.collapse').on('shown.bs.collapse', function () {
    var panelHeading = $(this).siblings('.panel-heading');
    panelHeading.find(".glyphicon-plus").toggleClass("glyphicon-minus glyphicon-plus");
    panelHeading.css("background", "blue");
}).on('hidden.bs.collapse', function () {
    var panelHeading = $(this).siblings('.panel-heading');
    panelHeading.find(".glyphicon-minus").toggleClass("glyphicon-minus glyphicon-plus");
    panelHeading.css("background", "red");
});

CHECK OUT THE UPDATED FIDDLE

Answer №2

Give this a shot:

$(document).ready(function(){
    $('.panel-collapse').each(function(i, el){
        if($(el).hasClass('in')){
            $(el).prev('.panel-heading').css("background", "blue");
        } else {
            $(el).prev('.panel-heading').css("background", "red");
        }
    });
});

Best regards, Frederic

Answer №3

Alright, here is the solution:

$(function(){

    $('.accordion-toggle').on('click',function(e){
    $('.panel-heading').removeClass('bgPurple');
    $(this).closest('div.panel-heading').addClass('bgPurple');
  });

});

To style it in css, simply add:

.bgPurple{
  background-color:purple !important;
}

This should work perfectly for you, hope this is what you were looking for! :-) Samantha

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

The Ajax upload feature is unable to handle JSON responses properly, resulting in a download popup

Currently utilizing the AJAX plugin developed by Andris Valums: AJAX Upload ( ) Copyright (c) Andris Valums The functionality is working well, except for an issue regarding sending JSON as a response. I have set the headers to 'Content-Type', ...

Unable to establish connection with server through Ajax request on HTML page

I set up a NodeJs server using the Express module. However, I am facing issues with implementing an AJAX request from an HTML page using $.ajax when clicking a button. I want to retrieve data from the server in either JSON or text format but for some reaso ...

What strategies can be used to scale up a website's images in proportion to their page views or traffic?

The situation: On my simple HTML website, I have a group of images placed side by side. Each image is connected to a specific article, and when you hover over the image, a detailed description of the linked article pops up in the center of the page. The o ...

Sending data from an AngularJS frontend to a Laravel backend using an HTTP

I've been researching, but I can't seem to make sense of anything. I'm new to Laravel and I want to use it as a backend for my AngularJS project. Since I have experience with Angular, here is the controller function where I make an HTTP call ...

What could be causing the error message about jQuery not being defined in this bookmarklet code, even though jQuery is already included

As I work on creating a bookmarklet, I encountered an issue with the code below. When I visit a page, it initially gives an error message saying "jQuery is not defined". However, upon clicking it again, the bookmarklet functions perfectly. var qrcodetog ...

Utilizing Lambda to Analyze PDF Documents with AWS Textract

Struggling with implementing Textract in Lambda to analyze PDF documents using JavaScript. Any assistance would be greatly appreciated. Below is the code snippet: const AWS = require("aws-sdk"); AWS.config.update({ region: proces ...

When a td element is clicked, the Textbox will also be clicked

Similar Question: Dealing with jQuery on() when clicking a div but not its child $(oTrPlanning).prev().children('td').each(function () { this.onclick = setCountClick; }); When a TD element is clicked, the function setCountClick() i ...

Enhance the Search Box with a Vibrant Glow Effect When in Use

I need help adding a glow effect color around a search field when a user clicks on it to type. I want the border to have a shadow and the glow effect to be orange. I have included the CSS below, but I'm unsure of what to change or add. Any assistance ...

Webpack 2 and Babel seem to be having trouble converting the code to ES2015

I've recently put together a sample project using webpack and started incorporating babel. Despite trying out various configurations from different sources, I'm still encountering issues with getting it to work properly. Below is my webpack.conf ...

Transferring a JavaScript variable to PHP using AJAX does not display any output

My code is not working as expected. I am trying to pass a JavaScript variable with Ajax to PHP when the submit button is clicked, but the result does not display the var_data variable from JavaScript. Can someone help me identify what is wrong with my code ...

Async problems arise when using nested forEach loops, causing them to complete at varying speeds

Using express, neat-csv, and mongoose has led me to a scenario where I need to verify the existence of a series of users when a batch register call is made from a .csv file. The current process works smoothly as long as all information is input correctly, ...

What causes the textbox to lose its masking after a postback?

I have sought answers to this question multiple times across various platforms, but unfortunately I haven't found a solution yet. Nevertheless, I remain hopeful and am reaching out again for assistance. My issue involves applying JqueryMasking to a t ...

Eliminate an element's attribute value using jQuery

$("#options").find("a").click(function() { var sendbuttonval = $(this).attr('id'); document.querySelector('#save_option').addEventListener('click', function() { var date = document.querySelector('.date&apo ...

meteor Error: IDENTIFIER is missing

I recently started following the Angular-Meteor framework tutorial () but I encountered an error towards the end that I'm struggling to resolve. Despite my efforts in looking for a solution, my limited understanding of the framework seems to be hinder ...

What steps can I take to ensure that the elements are in the same row instead of being displayed in three separate rows?

(I'm a beginner in web development and need some help) Is there a way to align elements into the same row instead of stacking them up in separate rows? I'm working on creating a header bar similar to the one on the Naive UI Documentation Website. ...

Issue: Amcharts Dataloader plugin does not load the chart when the PHP file outputting JSON is located in the include folder

Currently, I am utilizing Amcharts to generate column charts that can be rotated into horizontal bar charts. To achieve this, I am leveraging the dataLoader plugin provided by Amcharts. This plugin allows me to connect to a PHP file which in turn communica ...

Utilizing @ symbol for passing arguments to $resource

Within my controller: UserResource.find({ userId: userId }, function (records) { $scope.user= records; }); In the resource I've created: angular.module("main_k"). factory("main_k.service.resou ...

View information on Android without the need for any HTML formatting

I have a SQLite table filled with records that contain HTML tags. I need help figuring out how to properly display these records in my application so that users only see the actual content without the tags. Any ideas on how to achieve this? Below is the c ...

Sending data from TextBox as json format

JavaScript Code: var latitude = document.getElementById("<%=txt_Lat.ClientID %>").value; var longitude = document.getElementById("<%=txt_Long.ClientID %>").value; var jsonData = {latitude: latitude, longitude: longitude}; var jsonString = JSO ...

Eliminating redundant files in the upload section

Currently, I am using lodash clonedeep for the purpose of uploading files. I managed to write a function that prevents users from uploading identical files. However, I have encountered an issue where if I delete a file after uploading it, it remains in th ...