Deleting images based on their class through a loop

Currently, I am in the process of constructing a carousel using data retrieved from an endpoint. The challenge I face is determining the appropriate image size to request from the server. To address this, I perform some front-end processing to dynamically decide the size of each image to use. Subsequently, I hide images that are not selected for display. However, my performance is being impacted as the display:none method still triggers HTTP requests. I attempted using remove() instead of .css('display','none');, but encountered issues since both methods remove other images due to the shared class.

Is there a way to remove specific images within the loop without affecting others?

This is the sample data fetched from the server (components).

<div class="foo-grid-img">
    <img src="https://cdn.com/image/1.jpg" class="foo-big" />   
    <img src="https://cdn.com/image/2.jpg" class="foo-small" /> 
    <img src="https://cdn.com/image/3.jpg" class="foo-horizontal" />    
    <img src="https://cdn.com/image/4.jpg" class="foo-vertical" />  
</div>  

<div class="foo-grid-img">
    <img src="https://cdn.com/image/a.jpg" class="foo-big" />   
    <img src="https://cdn.com/image/b.jpg" class="foo-small" /> 
    <img src="https://cdn.com/image/c.jpg" class="foo-horizontal" />    
    <img src="https://cdn.com/image/d.jpg" class="foo-vertical" />  
</div>

var fooConf = [['big'],['vertical','big'],['small','small','horizontal'],['vertical','big','horizontal','horizontal'],['vertical','big','horizontal','small','small']];

for (var i = 0; i < components.length; i++) {

    // elided

    var fooClass = fooConf[components.length-1][i];

    if("foo-"+fooClass != fooBig.attr("class")) {
        cItem.find('.foo-big').css('display','none');
    }
    if("foo-"+fooClass != fooSmall.attr("class")) {
        cItem.find('.foo-small').css('display','none');
    }
    if("foo-"+fooClass != fooHorizontal.attr("class")) {
        cItem.find('.foo-horizontal').css('display','none');
    }
    if("foo-"+fooClass != fooVertical.attr("class")) {
        cItem.find('.foo-vertical').css('display','none');
    }

}

The desired outcome after processing should resemble the following HTML structure:

<div class="foo-grid-img">
    <img src="https://cdn.com/image/1.jpg" class="foo-big" />   
</div>  

<div class="foo-grid-img">  
    <img src="https://cdn.com/image/d.jpg" class="foo-vertical" />  
</div>

Answer №1

After receiving updated information from the question, the code has been adjusted accordingly:

var $imageDivs = $('div.foo-grid-img'); //select all sets

//loop through all sets and remove images that do not belong in the corresponding fooConf[i]
for(var i = 0; i < fooConf.length; i++) {
    $imageDivs[i].find('img').each(function(){ 
        var $this = $(this);
        var className = $this.attr('class');
        if(!$.inArray(className.replace('foo-', ''), fooConf[i])){
            $this.hide(); //or remove()
        }   
    });
}

Answer №2

To apply styles to a specific element by targeting its class, you can use the index of that element. If you wish to temporarily hide and then display it again, consider using .toggle(). However, if your intention is to permanently remove it, then you can use .remove() method.

for (var i = 0; i < components.length; i++) {

    // code snippet has been shortened

    if("bar-"+barClass != barBig.attr("class")) {
        cItem.find('.bar-big')[i].toggle();
    }
    if("bar-"+barClass != barSmall.attr("class")) {
        cItem.find('.bar-small')[i].toggle();
    }
    if("bar-"+barClass != barHorizontal.attr("class")) {
        cItem.find('.bar-horizontal')[i].toggle();
    }
    if("bar-"+barClass != barVertical.attr("class")) {
        cItem.find('.bar-vertical')[i].toggle();
    }
}

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

``How can I lock the top row of an HTML table containing input fields in place while

Below is the table structure: <table> <tr> <th>row1</th> <th><input type="text"></th> <th><input type="text"></th> <th><input type="text"></th& ...

Having trouble retrieving state parameters when trying to launch a modal in AngularJS

When the "view detail" link is clicked, I wanted to open a modal for a detailed view of a specific user. However, I encountered an issue where I couldn't retrieve the user ID in the resolve attribute of $uibModal.open(). Strangely enough, the ID is av ...

Tips for showing an Object with nested Objects in Vue.js

Looking for guidance on displaying a JSON object in Vue.js with the following structure: { "1": [ "15-16", "16-17", "17-18", "18-19" ], "2": [ & ...

Place a written message on an picture

<head> <style> .relative{position:relative; width:600px;} .absolute-text{position:absolute; bottom:1; font-size:12px; font-family:"vedana"; background:rgba(251,251,251,0.5); padding:10px 20px; width:10%; text-align:center;} </style> < ...

What is the process to retrieve the username from my system and display it in a web browser?

Seeking assistance to retrieve my system's username and display it on a web browser. Currently, I have been using ActiveXObject method, which successfully retrieves the username, but has drawbacks such as requiring ActiveX to be enabled and only works ...

After the main page is loaded, the div will be dynamically populated with HTML content. How can we confirm that it has finished

I recently took over a project where a page loads and then code attached to that page populates a div with dynamically generated html – essentially filling an existing div with a string of html elements. Within this string are links to images, among oth ...

Is there a way to access hover effect information in Atom editor similar to how it appears in VScode?

Is there a specific plugin required in Atom to display information when hovering over variables, objects, or functions similar to intellisense? VSCode does this automatically, but I am looking for the same functionality in Atom. https://i.stack.imgur.com/ ...

Tips on altering the color of a circle's radius within Google Maps

I'm trying to add a circular radius on a Google Map. Even after reviewing the Google Maps API documentation, I'm still unsure of how to accomplish this task. Below is the code snippet I have been working with: const MyMapComponent = compose( ...

What is the best way to manage json-parse errors in a node.js environment?

After countless hours of research, I am still unable to find a solution to my seemingly simple and common problem: In Node.js using Express, I want to retrieve JSON-data via http-POST. To simplify the process, I intend to utilize the app.use(express.json( ...

Troubleshooting a hover problem in CSS navigation bar

Having some trouble with the CSS menu on my website click here. I've tried adjusting the code, but can't seem to get all the menu levels to line up properly. As a beginner in CSS, I'm sure I'm overlooking something simple. When hovering ...

Heroku is rejecting the Discord token, but it is functioning properly in Visual Studio Code

I am facing an issue with an invalid token error on Heroku, even though the token in my main.js file on Git is the same as the one I have in Visual Studio Code. Interestingly, Heroku claims it's an invalid bot token while the Discord bot token from VS ...

Mudblazor - Tap or click within the designated area to trigger the drag and drop functionality

I have incorporated the Mudblazor CSS framework into my Blazor WebAssembly project. Within the drag and drop zone, I have included a button that is supposed to remove each uploaded image. However, when I click on the remove button, it only opens up the fi ...

Why won't my sticky element function properly with the position attribute set to sticky?

Hey there! I've been diving into learning all about CSS positions and have nailed down most of them. However, for some reason, the sticky position just won't cooperate and is stubbornly acting like a relative one instead. Check out my HTML snipp ...

Learn how to execute shell commands on a Linux server from a Node.js application by utilizing Socket.io for establishing a connection. This includes tasks such as running "ls -ltr", changing

After successfully establishing a connection with my Linux server, I aim to execute shell commands for automation purposes such as changing directories and creating new folders. The main objective is to connect to the Linux server through a webpage, wher ...

Is there a way to dynamically expand and collapse all table rows, with the latest row always remaining visible, using pure JavaScript?

I have a form input field where I enter data. The entered data is then displayed in a table as a new row, with the most recent entry at the top. What I want to achieve is to show only the newest row in the table and hide all other rows. When I hover over ...

Absolute positioning causes an element's height to increase

As I delve into the realm of typographical animations and seek to calculate the baseline of a font at various sizes, I've stumbled upon a peculiar discovery: It appears that the height values of elements tend to increase in an erratic manner when thei ...

Searching in Django utilizing jQuery keyup

When implementing a search functionality using the jQuery keyup function, I have set up my views to display the searched contacts in a template. Here is how my views are structured: def contacts_profile(request, search_id=None): contact = Invitation.o ...

Problem with Array Serialization

I have a situation where I am serializing information using jQuery and storing it in a MySQL database: $(function () { $("#sortable").sortable({ stop: function (event, ui) { $("#q35list").val($(this).sortable('serialize') ...

Is your $http request causing an XML parsing issue?

I'm attempting to utilize the $HTTP method from angularJS to access my restful web service. On entering my web service URL in the browser, I receive a result of APPLICATION/JSON type. {"id":20418,"content":"Hello, World!"} The URL for my web servic ...

Determine the exact location of a click within an SVG element

This block of HTML includes SVG elements: <div class="container"> <div class="spacer"></div> <svg> <g id="polygonGroup" transform="translate(80, 50)"> <polygon points="-60,-10 -35,-30 -10,-10 -10,30 -60,30"&g ...