Using jQuery to select the third element from every group of six

I am attempting to select the 3rd .foo element out of every set of 6. To clarify, here is a brief example:

1
2
3 (this)
4
5
6
1
2
3 (this)
4
5
6
and so on...

So far, I have only managed to target every 3rd element, which is not exactly what I need because it also selects the first .foo: http://jsfiddle.net/neal_fletcher/Bb4Hv/

$('.foo').each(function() {

    if(!($('.foo').index(this) % 3)) {

        $( this ).css( "background-color", "red" );
    }

});

If anyone has any ideas on how to achieve the desired outcome as per my illustration, I would greatly appreciate the help!

Answer №1

In my opinion, the nth-child() method suggested by @Arbel is preferable, but to make your question code work with a small modification, you can do the following:

$('.foo').each(function() {    
    if(!(($('.foo').index(this)-2) % 6)) {    
        $( this ).css( "background-color", "red" );
    }    
});

Essentially, what you want is every 6th element, starting from an offset of 2.

On a side note, the jQuery function 'each' actually passes in both the index and the element itself (native element) to the iterator function. So, you could rewrite the above code like this:

$('.foo').each(function(i,ele) {
    if(!((i-2) % 6)) {
       $(ele).css( "background-color", "red" );
    }
});

EDIT

I mentioned that I preferred the nth-child approach, however, considering some of the comments, using nth-of-type may be more suitable for your needs.

For more information, check out these links:

Mozilla nth-of-type

and

CSS Tricks comparison of the two

Here's an example using nth-of-type:

.foo:nth-of-type(6n-3)
{
    background-color: red;
}

NOTE: The reason for the difference in the formula to determine the element you want (i.e. i-2 % 6 or 6n-3) is because JavaScript starts indexing at 0 as the first element, while CSS begins with 1 for the n in nth-child or nth-of-type selectors.

Answer №2

To easily target every 6th element minus 3, you can use the CSS selector nth-child(6n-3)

Check out a live demonstration: http://jsfiddle.net/E8C7F/5/

If you prefer using jQuery, here is an example:

$('.bar:nth-child(6n-3)').css("color", "blue");

You can view your updated demo with jQuery here: http://jsfiddle.net/D4R9S/3/

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

Explore within the <li> element using jQuery

Need assistance on how to search within the li element. The li list consists of employee names in the format [surname,firstname]: Venkata,Anusha Raju,Suma Here is the HTML CODE: <input type="text" id="comboBox" placeholder="Search.." /> < ...

Function executed prior to populating $scope array

I encountered an issue with AngularJS involving a function that is called before the data array is filled. When the function is invoked in ng-init, the $scope.bookings array is not yet populated, resulting in empty data. My objective is: Retrieve all book ...

Using @carbon/react in conjunction with Next.js version 13 leads to unconventional styling

Here's what I did to set up my Next.js application: npx create-next-app@latest I then installed the necessary package using: npm i -S @carbon/react The global styles in app/globals.scss were customized with this code snippet: @use '@carbon/reac ...

What is the abbreviated term for personalized elements in React Native development?

After discovering that custom components can be created like this: const CustomComp=()=>{ console.log('Created custom comp'); return(<View></View>); } export default function App(){ return(<View style={{flex:1}}> &l ...

Ways to exclusively display map items matching those in the array

Hey everyone, I'm dealing with a map that looks like this: Map { '708335088638754946' => 38772, '712747381346795670' => 12051, '712747409108762694' => 12792 } Alongside this map, I also have an array: let arr ...

What is a way to transfer an Object from one Vue.js component to another without relying on vuex?

Using vue-router in app.vue, I defined the two components as shown below: <div class='app'> <div class='nav'> <router-link to='/a'>to A component</router-link> <router-link to= ...

Move content off the screen using CSS3 translation

Throughout various projects, I have encountered the need to make elements on a webpage translate out of view (essentially making them fly out of the document). The idea was that by simply adding a class to the element, the CSS would take care of the animat ...

Error: Attempting to access the 'getCroppedCanvas' property of an undefined value in VueJs

I've been exploring the vue-cropperjs library, but every time I execute the code, I encounter error messages: Uncaught TypeError: Cannot read property 'getCroppedCanvas' of undefined Uncaught TypeError: Cannot read property 'replace&ap ...

In my current Next.js project, I tried setting up a new [collectionId].jsx file within the pages directory, but I am facing issues with getting

In my current next.js project, I recently created a file named [collectionId].jsx within the pages directory. Interestingly, I noticed that Tailwind CSS does not seem to work properly with this file. However, when I renamed the file to [collectionId].js wi ...

I'm looking to generate a semicircle progress bar using jQuery, any suggestions on how

Hi there! I'm looking to create a unique half circle design similar to the one showcased in this fiddle. Additionally, I want the progress bar to be displayed in a vibrant green color. I've recently started learning about Jquery and would apprec ...

Navigating a JSON message received from a websocket: Best practices

How can I cycle through various types of JSON messages received from WebSocket and trigger a function based on the type to modify observables in MobX? Can anyone assist with this? For instance, one of the simple messages looks like this: { name: "as ...

What is the method or variable called "afterShow" used for in FancyBox V4 and how does it differ from its counterpart in JQuery-FancyBox V3?

We previously utilized the V3 edition of Fancybox, incorporating our increaseImageClicks and increaseVideoClicks functions within its afterShow function: /* FANCYBOX OLD (https://web.archive.org/web/20210325170940/https://fancyapps.com/fancybox/3/docs/): * ...

The dropdown-menu-end class in Bootstrap 5 navbar is not activating on hover as expected

My Bootstrap navbar has right-aligned dropdowns, but when I try changing the trigger to hover, the .dropdown-menu-end class doesn't work as expected. I attempted using CSS for the hover effect: .dropdown:hover .dropdown-menu { display: block; mar ...

Limit access to Google Fusion Table to specific types of maps. Eliminate Google Fusion Table for selected map formats

Currently, I am in the process of creating a web map using the Google Maps Javascript API. My objective is to display a Google Fusion Table containing buildings in Boston exclusively on a stylized map named "Buildings." When I switch to the Buildings map t ...

Encountering issues with uploading files using ajax

Developing my own custom CMS requires me to enable file and image uploads. Despite attempting to integrate the blueimp uploader, I encountered difficulties. The goal is to transmit formData through a jquery script to interact with my CMS. In PHP code (rec ...

Component rendering based on conditions is not working properly when using Next.js, especially on the initial load

While utilizing Ant Design and a Custom Stylesheet, I have encountered an issue where the style appears broken upon first load. However, if I navigate to another page and return to the original broken page, it displays correctly. This problem only occurs d ...

Verify if the screen is in full view by monitoring document.fullscreenElement within Vue3

Is there a way to determine when the document is in fullscreen mode? I attempted to monitor document.fullscreen with the following code, but it was not successful: watch(document.fullscreenElement, (newValue) => { fullScreenActivated.value = newValue ...

Converting DateTime objects into JSON format for use in AJAX calls

When utilizing my AJAX method, it returns a view model that is serialized as a data structure using JavaScriptSerializer().Serialize(). Among this data are several nullable DateTime? properties. I recently discovered that these dates appear in JavaScript ...

Execute a PHP script to retrieve data from a database based on the content of a text element

I'm currently working on a web-based system and I'm wondering if it's possible to retrieve a Name based on the number entered in a text box. Here is what I have attempted so far, but I know it's not functioning properly. Is there an alt ...

Changing React Phone Number input field's default style: A step-by-step guide

Is there a way to modify the appearance of the react-phone-number-input component using this npm package: https://www.npmjs.com/package/react-phone-number-input? I am working with React Hook Form and Tailwind CSS alongside this component. However, I' ...