Make sure to always verify the condition every time

Below is the code I'm using to render multiple instances:

I have two sections, one with the 'show-all' class and the other with no class.

If the 'show-all' class is not present, the countIncrease function needs to be executed. If the class is present, there is no need to run the function.

Each time, the section needs to check for the presence of the class.

class Grid {
    init() {
        $('.grid').each(function() {
            const $this = $(this);
            // getting values & url from html
            const dropDownUrlpath = $this.find('.grid__dropdown-select').attr('data-ajaxurl');
            const hasClass = $this.find('.grid').hasClass('grid_showall');
            
            function countIncrease() {
                let limit = parseInt($this.find('.grid__component').attr('data-initcount'), 10);
                const incrementalCall = parseInt($this.find('.grid__component').attr('data-incrementalcount'), 10);
                $this.find(`.grid__content > .grid__component:gt('${limit - 1}')`).hide();
                if ($this.find('.grid__content > .grid__component').length <= limit) {
                    $this.find('.grid__cta').hide();
                }
                else {
                    $this.find('.grid__cta').show();
                }
                $this.find('.grid__cta').on('click', function(event) {
                    event.preventDefault();
                    limit += incrementalCall;
                    $this.find(`.grid__content > .grid__component:lt('${limit}')`).show();
                    if ($this.find('.grid__content > .grid__component').length <= limit) {
                        $this.find('.grid__cta').hide();
                    }
                });
            }
            
            if (hasClass.length === true ) {
                console.log('class exist-----'+ hasClass);
                countIncrease();
            }
            $this.find('.grid__dropdown-select').on('change', function() {
                const optionValue = this.value;
                $.ajax({
                    url: dropDownUrlpath + optionValue,
                    success(result) {
                        $this.find('.grid__content').html(result);
                        countIncrease();
                    }
                });
            });
        });
    }
}

I've written an if condition but it only runs once and gives a false result in both scenarios,

if (hasClass.length === true ) {
    console.log('class exist-----'+ hasClass);
    countIncrease();
}

How can I handle this...?

Answer №1

Isn't it necessary to include a parameter in the .hasClass method for specific checking?

if ( $this.hasClass ('some class') === true ) {
alert('something');
}

Alternatively, you can use if(hasClass.length > 0){}

Answer №2

Store the 'checking' class in a variable by locating it within the parent div,

const hasCheckingClass = $this.find('.grid').hasClass('grid_checking');

Retrieve the attribute value for the first element only in the selected group using the .attr() method

const classValue = hasCheckingClass.attr('class');

Verify the condition, with

if (classValue !== 'grid_checking') {
    incrementCounter();
}

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 could be causing the jQuery spritely animation to display an additional frame upon the second mouseenter event?

I have been experimenting with CSS sprites and the jQuery plugin called spritely. My goal is to create a rollover animation using a Super Mario image. When the mouse hovers over the Super Mario <div>, I want the animation to play forward. And when t ...

Encountering "Duplicate identifier" issues when using Angular2 and TSD

I am currently in the process of migrating a project from Angular 1 to Angular 2. The project involves client and server code, with some shared components. My goal is to implement Angular 2 on the client side by following the guidelines outlined in the ng2 ...

The error message "Property 'map' is not found on type 'User' in React with typescript"

I am currently experimenting with React using TypeScript. I have set up useState with an object but I am encountering issues trying to use the map function with that object. Below is the error message I am facing: Property 'map' does not exist ...

Ways to implement HemisphereLight with ShaderMaterial?

I am facing an issue where I am trying to light an object that has been created with ShaderMaterial using HemisphereLight, but the object does not appear to be affected by any of the lights. I have tested it with various other lights as well, and none seem ...

Creating an Angular form group that includes dynamic form controls with custom form control names

Seeking to implement a formGroup that dynamically adjusts based on JSON data like this: const LIMITS: Limit[] = [ { id: 'limit1', value: 1000, disabled: false }, { id: 'limit2', value: 500, disabled: tru ...

Why is the image not appearing in the Popover?

When hovering over, the popover only shows the title and not the image. Snippet of Code: <script type="text/javascript"> $(document).ready(function(){ var img ='<img src="/assets/Excel_1.png">'; $("#blob").popover({ title: ' ...

What is the best way to secure the installation of python packages for long-term use while executing my code within a python shell on NodeJS?

I have been encountering difficulties while attempting to install modules such as cv2 and numpy. Although I have come across a few solutions, each time the shell is used the installation process occurs again, resulting in increased response times. Below i ...

What could be causing my browser to display "uncaught referenceerror" in this situation?

Just running some browser tests to troubleshoot - everything's smooth sailing until this line is reached: responseJson = JSON.parse(localReq.responseText); So, when I evaluate JSON.parse(localReq.responseText), the correct value comes through. But a ...

A guide to navigating a JSON array

Utilizing node js, I have extracted the following array by parsing through multiple json files to find a specific value. My json files consist of a collection of IDs with their respective status: isAvailable or undefined. https://i.sstatic.net/AlpVk.png ...

Click on an element that is nested within another element that can also be clicked on

I'm facing a challenge while attempting to create an accordion inside another accordion. The issue arises with the nested elements and their behavior upon clicking. Essentially, I have a parent div with the class .applicant, which expands on click by ...

Is it possible to spread an empty array in JavaScript?

Whenever I run the code below, I encounter the error message Uncaught SyntaxError: expected expression, got '...': [1,2,3, (true ? 4 : ...[])] I'm wondering if spreading an empty array in that manner is allowed? ...

"I'm looking for a way to store and fetch TypeScript objects with PouchDB. Any suggestions on

As someone who is new to typescript and web development, I am eager to incorporate PouchDB into my typescript project to store my objects. Despite the lack of documentation, I am struggling to find the correct approach. I have created typescript objects t ...

Is there a term similar to "Rise above the Rest" in the world of Web Development?

Hey, I've encountered a new issue right now. Currently, I have two elements that are fixed to the top and bottom of the page. However, the elements in between them are overlapping the top element. Even though I tried keeping both elements fixed, th ...

Do ES6 features get transpiled into ES5 when utilized in TypeScript?

After implementing ES6 features such as template strings, arrow functions, and destructuring in a TypeScript file, I compile the code to regular JavaScript... Does the TypeScript compiler also compile the ES6 syntax, or do I need to utilize another compil ...

What is the best way to retrieve the specific property from a bound function?

I'm looking to retrieve the value of a specific property from a function that has already been bound. function foo(){ console.log(this.a) } const bar = foo.bind({a:1}) bar() // Outputs 1 bar.getThis() // expected result is { a: 1 } Given the code ...

Unable to call a component's method from a different component in Angular 7

How can I call the toggleSidebar() method of the SidebarComponent from the HeaderComponent using the callToggleSidebarOnToggleSidebarBtn() method? I am encountering an error that I cannot comprehend. What is the correct way to use a method of one component ...

Having trouble compiling Vue.js for Internet Explorer 11

After seeking help on Stack Overflow and conducting extensive research, I have finally configured my babel.rc file as follows: { "presets": [["env", { "modules": false, "uglify": true, "targets": { "browsers": ["> 1%", "last 2 versi ...

Processing Ajax before callback has always been a crucial step in web development. This involves utilizing features like beforeSend, ajaxStart

I am currently facing an issue with the ajax call in jQuery. What I am trying to achieve is to empty certain divs, hide a container, then make an ajax request to populate the divs again and show them. However, my code seems to be hiding the content before ...

Utilizing a class function within the static method `getDerivatedPropsFromState`

I've been updating the deprecated life-cycle method componentWillRecieveProps() to its new replacement static getDerivatedPropsFromState(). The issue I'm encountering with this update is that componentWillRecieveProps() uses a class function int ...

Tips for adjusting the dimensions of a child element to match its parent in Angular 12 with Typescript

I have included the child component in the parent component and I am displaying that child component within a col-md-8. What I want to achieve is to highlight a specific div in the child component with additional text, making it equal in size to the parent ...