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

"Trouble with Angular JS foreach loop: only the final item in the array

Struggling to loop through each item object in a JSON data set and evaluate its value using angular.forEach(). However, only the last item is being returned, making it impossible to perform any meaningful evaluation. Oddly enough, when using console.log(), ...

AngularJS directive created for validation on blur

I am striving to replicate some of the features found in Angular 1.3.X for the app I am developing, with a particular focus on ensuring compatibility with IE 8. Unfortunately, this constraint means that I cannot utilize version 1.3.X. I have encountered di ...

Feed information into a Select element from the Material UI version 1 beta

Having trouble populating data from a < Select > component in Material UI version 1.0.0.0 beta. Snippet of my code: This section is located inside the render() method. <Select value={this.state.DivisionState} onChange={this.handleChangeDi ...

Group the JSON data in JavaScript by applying a filter

I have a specific json object structure with keys cgi, tag and name, where the cgi key may be repeated in multiple objects. If any cgi has the tag 'revert', then that particular cgi should not be returned. [ { "cgi": "abc-123 ...

Some suggestions for updating two div elements using only one Ajax response

My website features a signin() button that I want to enhance with ajax functionality. When the button is clicked, I need it to update two divs: one displaying a personalized welcome message, and the other showcasing a statistics table in a different locati ...

Is there a way to accurately retrieve the width of an element within setInterval without any delay?

I'm currently experimenting with increasing a progress bar using the setInterval function. So far, it seems to be functioning properly. var progressBar = $('.progress-bar'); var count = 0; var interval = setInterval(function () { va ...

Adding a Bold Headline in Select2: A Quick Guide

I have thoroughly searched through all of the select2 documentation but unfortunately, I could not find any information on how to add bold headlines. Can anyone please provide a full code example (including CSS) on how to accomplish this? ...

Enhancing the appearance of CSS Tables

I need help with applying a gradient line below each row of data that I am fetching from my database and displaying in a <table>. I've been able to achieve the design using an <hr> element, as shown here: http://jsfiddle.net/ghrw3k8e/. Ho ...

I have successfully converted an SQL Join query into JSON, but now I am unsure of how to interact with the

I recently ran an SQL Join on two tables and obtained the following results: _____People_____ name: "Jane" age: 35 job_id: 1 _____Professions_____ job_id: 1 title: "Teacher" "SELECT * FROM People INNER JOIN Professions ON People.job_id = Professions.job ...

Synchronous: Establishing a connection to MongoDB once the server has successfully launched

I am curious to understand the interaction between Node.js asynchronous functions and MongoDB. If the server initializes before establishing a connection, and if my templates or Ajax requests rely on database data, will the serving of the HTML fail or will ...

Receiving a Javascript Callback from Paypal

Is it possible to receive a JavaScript callback after a successful PayPal purchase made using a button? I am aware of IPN, but it requires a return URL. My main goal is to simply determine if a user has completed a purchase with the button. ...

Creating randomized sequences using JavaScript

One of my hobbies involves organizing an online ice hockey game league where teams from different conferences compete. It's important to me that every team gets an equal number of home and away matches throughout the season. To simplify this task, I&a ...

php retrieve and show data from MySQL database based on selection from dropdown menu

I've encountered an issue where I can retrieve data from a database and display it in a drop-down menu, but I'm not sure how to use the same drop-down list as input within a form. My code retrieves project names from the database and displays the ...

Attempting to grasp the concept of memory leakage in a more thorough manner

As I dive into the world of frontend development and start learning Vue.js, I came across a paragraph in the tutorial that caught my attention: Vue.js makes rendering a template seem simple, but under the hood it does a lot of work. The data and DOM are ...

Express route encountered an error with an undefined value

Here's the method declaration: exports.postRedisValue = function(req,res) { let keyRedis = req.body.key; let valueRedis = req.body.value; console.log(keyRedis); //displays as undefined if(keyRedis && valueRedis){ ...

Boost Engagement with the jQuery PHP MySQL Like Feature

Seeking assistance in creating a like button with PHP, MySQL, and jQuery. I'm encountering an error but unable to pinpoint its source. Can anyone provide guidance? The project involves two pages: index.php & callback.php INDEX $k = 1; //POST ID $n ...

Exploring Object Arrays with Underscore.js

Here is an array of objects that I am working with: var items = [ { id: 1, name: "Item 1", categories: [ { id: 1, name: "Item 1 - Category 1" }, { ...

What is the best way to transfer a value to the database using a distinct module?

I have recently set up a basic express project and added a file named lib/userhandler.js in the main directory. //lib/userhandler.js exports.addUser = function(req, res){ // Accessing our internal database variable var db = req.db; // Retrieving ...

Creating a double-layered donut chart with Chart.js

I'm attempting to create a unique pie chart that illustrates an array of countries on the first level and their respective cities on the second level. After modifying the data in a JSON file to align with my goal, it doesn't seem to be working a ...

Error: AppModule requires an array of arguments in order to function properly

Upon successfully compiling my Angular application and running ng serve, I encountered the following error in the browser console. AppComponent_Host.ngfactory.js? [sm]:1 ERROR Error: Arguments array must have arguments. at injectArgs (core.js:1412) at c ...