What is the best way to refine my selection of elements within a jQuery object?

function initializeItems($items, current, count) {
    $items.removeClass('z-item-current');
    $items.each(function(index) {
        var $self = $(this);
        $self.data('z-item-index', index);
        if(index === current) {
            $self.addClass('z-item-current z-item-show');
            var pre = current - 1,
                next = current + 1;
            pre = pre < 0 ? count - 1 : pre;
            next = next > count - 1 ? 0 : next;
            $($items[pre]).addClass('z-item-previous z-item-show');
            $($items[next]).addClass('z-item-next z-item-show');
        }
    });
    // reselect or filter $items
    // if has z-item-show class, show it; otherwise, hide it.
};

Looking at the code above, the objective is to reselect/filter a jQuery object. Specifically, the goal is to divide $items into two categories: $items with z-item-show class and $items without z-item-show class.

Currently, one approach is using $items.each, while another is using $items.parent().find.

Are there any more elegant approaches to achieve this?

Answer №1

To easily target elements with specific classes, you can utilize the filter and not methods:

$elements.filter('.target-class').show();
$elements.not('.target-class').hide();

While this approach is cleaner than using $elements.each(), it may be slightly less efficient due to executing two loops.

Answer №2

In order to effectively manage the manipulation of both existing and new previous/next/current items, you can incorporate all necessary functionalities within your current each function. By determining its position relative to the present index, you can effortlessly add or remove classes accordingly:

function initializeItems($items, current, totalCount) {
    $items.each(function(index) {

        var $element = $(this);
        $element.data('custom-index', index);

        if(index === current) {
            // current item
            $element.addClass('custom-current custom-display')
                .removeClass('custom-next custom-previous');
        }
        else if(index === (current == 0 ? totalCount - 1 : current - 1)) {
            // previous item
            $element.addClass('custom-previous custom-display')
                .removeClass('custom-next custom-current');
        }
        else if(index === (current == totalCount - 1 ? 0 : current + 1)) {
            // next item
            $element.addClass('custom-next custom-display')
                .removeClass('custom-current custom-previous');
        }
        else {
            // none of the above - clear all classes
            $element.removeClass('custom-next custom-previous custom-current custom-display');
        }
    });
};

Access JSFiddle sample here

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

Is the model being neglected in the world of MVC and jQuery?

Currently in the process of developing an ASP.NET MVC 3 web application and I have a strong affinity for jQuery. I am at a crossroads when it comes to deciding on the design approach, with two main options currently under consideration: One idea is to ...

Transform page appearance using CSS exclusively, without altering DOM structure

I have a structure that must remain unchanged for various reasons. Here is the current layout: <h1>heading</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. SeLorem ipsum dolor sit amet, consectetur adipiscing elit. SeLore ...

CSS: Ensuring the width is adjusted to the content or wrapper that is wider

I am facing an issue with mouse-over highlighting on a set of list items. Below is the HTML structure I am working with: <div id="wrapper"> <div id="box"> <div class="item">Lorem ipsum dolor sit amet, sit nonumy utamur ponderum ex& ...

Still having trouble getting @font-face to work with Firefox and htaccess

I've been struggling to load my custom font in Firefox despite numerous attempts. Here is the @font-face property code I have placed in the head section: @font-face { font-family: 'MeanTimeMedium'; src: url('http://sweetbacklove.com ...

I am having trouble getting my JavaScript to load

I've hit a roadblock trying to understand why my JavaScript code isn't executing properly. Could someone kindly point out what I may have overlooked? :( JSFiddle Link HTML Snippet <div class="po-markup"> <br> <a href="# ...

Tips for creating fully stretched columns within Bootstrap framework

I have a simple code example available on codepen, but here is the markup for convenience: <div class="container my-container"> <div class="row m-row justify-content-between"> <div class="col-2 my-col">One of three columns</div& ...

Display or conceal a div based on the size of the screen using HTML and CSS

Hey there, I recently finished my first React Project and I’m wondering if there’s a way to hide the 'side-menu' section on mobile screens using CSS. Any suggestions? <div className='side-menu'> <SiderComponent /> < ...

Guide to creating an inline form that spans the entire width below the navbar logo within the "navbar" component

I'm new to working with bootstrap and trying to create an inline form in the navbar next to the navbar-brand. However, as I resize the window, the form ends up below the navbar-brand link and doesn't align properly, making it look awkward. Can so ...

Can a rotationX be applied within an existing rotationX?

I have a collection of 3 divs labeled a, b and c inside a container. The container is rotatedX by 90 degrees, giving the appearance that it is "lying on its back". Now, I am trying to rotate the a, b, and c divs so they appear to be "standing up" again. Ho ...

Enhancing a class's properties from its parent component using React

Recently, I decided to dive into React by taking on the challenge of rebuilding the Google Weather app. My main objective is to have the main section update whenever a day is selected. Initially, I believed that updating the props within handleSelectionAt( ...

Utilize jQuery to access and manipulate a JSON array object

Hi there, I am working with an ajax request that is returning the following data: [[{"totalloginhours":"11.17"}],[{"totalagents":"2"}],[{"totalapplications":"2"}]] I'm wondering how I can access this string using jQuery without needing to loop throu ...

Trouble with navigating to div using link

I’m in the process of developing a website where all the various sections are contained on the home page and I utilize jQuery scroll for navigation. Clicking on links in the navigation bar scrolls to the respective sections seamlessly. However, I encoun ...

Exploring JSON data for auto-complete suggestions

Upon receiving the object from the source, it looks like this - ["road",[["road",53,"0E"],["roadtrip",53,"1E"],["roadrunner",53,"2E"],["roadster",53,"3E"],["roadside",53,"4E"],["roadrage",53,"5E"],["roadcycling",53,"6E"],["roadsideamerica",53,"7E"]],{"k": ...

The graph from Flot is not showing up, and there are no error messages

Recently, I have been experimenting with creating a graph plot using flot. However, I've encountered an issue where the graph is not displaying as expected. Despite using developer tools and JSlint to check for errors in my JavaScript code, both tools ...

Switching List Icons when Hovering over Dropdown

Newbie Inquiry: I am working on a dropdown list featuring 10 items, each with black icons aligned to the right. I want to switch these icons to white when hovering over them. Appreciate any tips you may have! Thanks in advance! ...

Ways to automatically update a page once the form response is received

After scouring various websites, I still haven't found a solution to my issue. What I need help with is how to refresh a page once a successful deletion message is received for a specific row. My admin2.php page displays information about the admin fr ...

Display only certain links using CSS or JavaScript/jQuery within a widget that appears once the webpage is fully loaded

I'm currently facing an issue on a website that requires a solution involving jQuery/javascript, which I am not proficient in. After the page loads, javascript is executed which renders various html/css elements. The specific portion we are focusing ...

Unable to see background image inside div

Why is the background image not showing up in the left column? I've applied the CSS background-image to .left but it's still not working. Any suggestions on what might be causing this issue? It seems like a small problem, but it's really bot ...

set ajax url dynamically according to the selected option value

My form features a select box with three distinct choices <select id="tool" name="tool"> <option value="option1">Option1</option> <option value="option2">Option2</option> <option value="option3">Option3</ ...

Tips for shifting a designated row upward in Chrome using JavaScript

Currently, I am working on a Javascript function that moves up a selected row. However, the issue I am facing is that when the row moves up, the old row is not being removed. For instance, if I move up the 'bbbb' row, it successfully moves up bu ...