Add a class if the particular class is missing from the webpage

Seeking a solution in JS, I am facing a challenge in creating a series of elements with active states, each opening a caption below when clicked. Utilizing .addClass, .removeClass, and .toggleClass in combination, only one element can be active at a time.

View the result here. Feel free to request the lengthy HTML if needed.

Although I have made progress, I am unable to close the caption area once it has been opened. The absolute positioning of captions within a relative parent prevents them from influencing the parent's height. Despite using .lcs-closed in #landercaptions to open up space and remove the class when an element is active, I struggle to revert it when no elements are active.

I am contemplating an approach where if no element has the class .sh-active, I add the class .lcs-closed to #landercaptions. I have experimented with .hasClass post page load but haven't landed on a working solution.

These are snippets of my code:

<script type="text/javascript">
        $('#one').click( function() {
            $("#capone").toggleClass("lc-hidden");  
            $("#captwo, #capthree, #capfour").addClass("lc-hidden");
            $("#two, #three, #four").removeClass('sh-active');
            $("#one").toggleClass('sh-active');
            $("#landercaptions").removeClass("lcs-closed");
        } );
        // Additional click functions for elements two, three, and four
    </script>

How can I ensure that the page reverts to its original state where all elements are inactive (caption area closed)? Any suggestions on modifying the existing JS script are appreciated.

EDIT Including the corresponding HTML:

<div class="landercols">    
<div class="lcheader">
    <h1 class="center">GoParenting. For growing families.</h1>
</div>
// Nested divs for each step holder and corresponding captions
</div>

Answer №1

To determine if there are elements on the page with a specific class, you should check the number of items in the jQuery wrapper that is returned.

if ($(".sh-active").length == 0) { 
  //... 
}

Regarding @user5014677: !$(".sh-active") - always results in false.

console.log($(".existing-class").length);
console.log(!$(".existing-class"));
console.log($(".non-existing-class").length);
console.log(!$(".non-existing-class"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="existing-class"></div>
 

Since the goal is to have the code in the accepted answer, I am including a snippet from @mtm's response below:

$('#one').click( function() {
    $("#capone").toggleClass("lc-hidden");  
    $("#captwo, #capthree, #capfour").addClass("lc-hidden");
    $("#two, #three, #four").removeClass('sh-active');
    $("#one").toggleClass('sh-active');
    $("#landercaptions").removeClass("lcs-closed");
    if ($(".sh-active").length == 0) { 
        $("#landercaptions").addClass("lcs-closed");
    }
} );

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

Include a "remember me" feature in the Stripe form

I am currently working on an exciting project using Angular 6. Within my website, I have decided to integrate the Stripe payment system. However, I would like to incorporate a unique and default "remember me" feature offered by Stripe. <div id="card-e ...

Retrieve the overall number of Formik errors for a specific field array

In the given Yup validation setup below, there is a nested Formik FieldArray: parentLevel: Yup.array().of( Yup.object({ childrenLevel: Yup.array().of( Yup.object({ childName: Yup.string().required('Name is required') ...

When a function encounters an error, load a fresh page

I am facing an issue where I want to display a new error page whenever a function throws an error. The current situation is that when the getStockPoints function encounters an error and I handle it using try and catch block in app.js, the error is caught b ...

Is there a way to obtain an array after subscribing to an RxJS method?

I am struggling with the following code snippet: Rx.Observable.from([1,2,3,4,5,6]) .subscribe(x=>console.log(x)); Is there a way to modify this code so that instead of iterating through the array elements from the .from() method, I can return the enti ...

Stopping Accordion Title from Moving Vertically in Material-UI

Just finished creating this accordion which will be used as a menu item. However, I've encountered an issue where clicking on the Main title causes the accordion summary to move downward vertically. Any suggestions on how to keep the Main tile fixed ...

After adding more rows, the css formatting seems to disappear

After populating flexigrid using a JavaScript method from another .js file, I noticed that the CSS is lost once new rows are inserted. Surprisingly, other sections on the page are not affected. The code snippet I am using is as follows: var newTbl = &apo ...

Having trouble getting SCSS to function properly? (Updated Code)

Transitioning from CSS to SCSS is my current project. I decided to make the switch because of SCSS's nesting capabilities, which I find more convenient for coding. However, I'm facing some challenges getting it to work properly. In my regular CSS ...

Is it possible to send props to a component within the render method?

I have a button component in my render method (DownloadReportsButton) that will trigger a modal onClick and perform an API call. The logic for the modal and the API call have already been moved to the button component, but how do I pass my data (an array ...

Allow the json array to be transformed into a format suitable for input

Hey there, I've received a JSON array as the response of my ajax request: {"chart":{"2016-03-08":"1","2016-03-07":"4","2016-03-06":0,"2016-03-05" :0,"2016-03-04":0,"2016-03-03":"145","2016-03-02":0}} Now, I'm looking to create a chart using the ...

Alter the color of the " / " breadcrumb bar

Is there a way to change the color of the slash " / " in breadcrumb trails? I have tried adding CSS styles, but it doesn't seem to work. <ol class="breadcrumb" style="font-size: 20px;"> <li class="breadcrumb-item&q ...

the box is having trouble with its animation

This issue revolves around the use of CSS3 properties like -webkit-keyframes and -webkit-box-align. To learn more about this problem, please check out http://codepen.io/pleasureswx123/pen/fljFH /* sample css code */ <style> .box { di ...

The "if" statement carries out the identical action each time it is executed

Despite my efforts to toggle the value of the turn variable every time the if statement runs, I keep encountering the same outcome. It appears that turn consistently evaluates as 2. Below is the code snippet in question: $(function() { var turn = 2; ...

Working with regular expressions on fieldsets in JavaScript jQuery

I'm facing an issue with a JavaScript regexp and I could really use some assistance. Currently, I have an ajax query result saved in a variable (in this case, a regexp) and I am trying to only match the content within the fieldset tag. Here is a sni ...

Incorporating an Angular 2 Directive within the body tag of an

My goal is to create a custom directive that can dynamically add or remove a class from the body element in HTML. The directive needs to be controlled by a service, as I want to manage the visibility of the class from various components. Question: How ca ...

The issue of slides overlapping in a Javascript slideshow during auto play mode

I encountered an issue while creating an automatic slideshow with 4 slides. Upon autoplay for the first time, slide 1 overlaps slide 4, as well as slide 2 and 3. This only happens once after the site loads. However, on subsequent playthroughs or when using ...

Loading game resources in advance for future or immediate utilization

I'm currently developing a game UI that involves a large number of image files, totaling around 30MB in size. I've been caching these images to the disk using service workers, but some of them are quite large at 3MB each. Even when they are retri ...

Converting large JSON data (approximately 100MB) into an Excel file using JavaScript

As a beginner in the realm of REST technology, I find myself navigating through a JSON response received from a server and showcasing the data on the client side. Currently, I am faced with handling approximately 22MB of JSON data that needs to be exporte ...

% unable to display on tooltip pie chart in highcharts angular js

https://i.stack.imgur.com/Ccd7h.png The % symbol isn't displaying correctly in the highcharts ageData = { chartConfig: { options: { chart: { type: 'pie', width: 275, height: 220, marginTop: 70 ...

Exploring Unicode in JavaScript to iterate through emojis with different skin tones

Currently, I am facing an issue where Javascript splits emojis with different skin colors into multiple characters instead of treating them as one. Emojis with a yellow skin color work fine and give me the desired results. For example: let emojis = [..." ...

I often struggle with creating social media buttons using Material UI

https://i.sstatic.net/jmZKS.jpg https://i.sstatic.net/4RQwe.jpg Unfortunately, the code provided is not rendering social media icons or buttons as expected. In the initial lines, material UI icons/buttons were imported from the React Material UI library ...