How to choose the nth item from various lists using JQUERY

It's not possible to achieve this using pure css because nth-of-type only selects based on an element's parent relationship (w3schools). Therefore, I am seeking a jquery alternative that can be applied across multiple lists.

HTML:

<div class="container" id="videos">
   <ul class="thumbnails">
      <li class="tn">
         <img class="tn-img" src="img/thumbnails/placeholder.jpg" />
      </li>
      <li class="tn">
         <img class="tn-img" src="img/thumbnails/placeholder.jpg" />
      </li>
      <li class="tn">
         <img class="tn-img" src="img/thumbnails/placeholder.jpg" />
      </li>
      <li class="tn">
         <img class="tn-img" src="img/thumbnails/placeholder.jpg" />
      </li>
   </ul>
   <ul class="thumbnails">
      <li class="tn">
         <img class="tn-img" src="img/thumbnails/placeholder.jpg" />
      </li>
      <li class="tn">
         <img class="tn-img" src="img/thumbnails/placeholder.jpg" />
      </li>
   </ul>
   <ul class="thumbnails">
      <li class="tn">
         <img class="tn-img" src="img/thumbnails/placeholder.jpg" />
      </li>
      <li class="tn">
         <img class="tn-img" src="img/thumbnails/placeholder.jpg" />
      </li>
      <li class="tn">
         <img class="tn-img" src="img/thumbnails/placeholder.jpg" />
      </li>
      <li class="tn">
         <img class="tn-img" src="img/thumbnails/placeholder.jpg" />
      </li>
      <li class="tn">
         <img class="tn-img" src="img/thumbnails/placeholder.jpg" />
      </li>
   </ul>
</div>

JQUERY

$( "#videos li:nth-of-type(5n+1) img" ).css( "margin-left", "0px");

This code is still targeting :nth-of-type(5n+1) in relation to its parent (the unordered list). This is evident as the first list item in every ul is being selected. My objective is to select the 5th list item across all unordered lists, without considering their parent elements.

Answer №1

const list = $('#videos li'),
    idx = 0, // starting index
    increment = 5,
    selected = null;

while((selected = list.eq(idx)).length) {
    selected.addClass('highlighted'); // modify as needed
    idx += increment;
}

http://jsfiddle.net/1573ahug/


Edit: Alternatively, using a classic for loop to avoid repeated checks for length:

const list = $('#videos li'),
    startIdx = 0, 
    stepSize = 5;

for(let i=startIdx, len=list.length; i<len; i+=stepSize) {
    list.eq(i).addClass('highlighted');
}

http://jsfiddle.net/1573ahug/1/

Answer №2

Your .css() code had a formatting error with a : instead of a , and the selector wasn't functioning correctly. I'm not sure why it wasn't working as expected, but try using this updated code to achieve the desired result.

$( "#videos li:nth-of-type(5n+1)" ).find('img').css( "margin-left","0px");

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

Creating a dynamic design with a responsive background image and three columns of engaging content placed on top using Bootstrap

I'm struggling to translate a design mockup into Bootstrap 3.3.6 Here is an image showcasing the concept I am aiming for: https://i.sstatic.net/1jZmh.png The blue background represents an image, with grey text boxes overlaid on top (one of which in ...

Ensure that the div spans the entire width of the page, prioritize maintaining the aspect ratio, but allow for variable

I have a dilemma with a div containing multiple elements. My goal is to make the div 100% in width, while also attempting to preserve the aspect ratio if feasible. Should the enclosed elements exceed the div's boundaries, then the height will adjust a ...

Establishing a deadline for Firestore's Node.js library

When using the Firestore Node.js library, I often find that some operations, like fetching a document, can take longer than expected, sometimes even several minutes. I am looking to set a timeout or deadline of around 20-30 seconds for these operations. ...

What causes jquery to not trigger PHP when the HTML file resides in a different location?

In my project structure, I have a 'js' folder containing the jQuery function and a PHP script. The HTML file is located in a separate folder. Currently, the setup looks like this: /server/js/global.js /server/js/script.php /server/html/stude ...

Customizing TableRow Hover Effects in React with Material-UI

I've been spinning in circles with this issue. It seems like I just can't grasp how class overrides function in Material-ui. I attempted to follow the advice in this response: CSS on Material UI components However, it didn't produce any res ...

JavaScript - The function will not execute any code inside its body

When I try to call my constructor function, it stops at the function definition in the debugger and never reaches the actual function body. Is there a common reason for this issue that I might be missing? Here is an example of the code: myconstructor.js ...

Retrieving & Refreshing Data with ajax and Jquery

I have been working on developing a forum system using jQuery, PHP, Bootstrap, and other technologies. The forum allows users to post, delete, and edit their posts. I have implemented an edit button for the author of the post, which triggers a modal wind ...

Utilizing AJAX in Cordova to Generate Dynamic JavaScript Charts from JSON Data

Exploring the world of Cordova, I have delved into utilizing canvas Js for visualizing data in chart format. Following a helpful tutorial, I created a Json file and inserted the specified data as instructed, following each step diligently. The outcome matc ...

Retrieve information from various MongoDB collections

Greetings! I currently have a database with the following collections: db={ "category": [ { "_id": 1, "item": "Cat A", }, { "_id": 2, "item": "Cat B" ...

Troubleshooting: My Angular 2 Application is Unable to Perform HTTP

I've exhausted all options and I'm still unable to send an http request to my node server on heroku. I can access the route manually, so it's not an issue with the server. Below are snippets of my service and page: **Class is subscription.s ...

Error: The function Undefined is not recognized by express.io

Struggling to configure express.io with individual files for each route? Check out the examples provided. Currently, I have a typical Express setup that I want to transition to express.io: Project app.js routes servepage.js Views ...

How to choose a javascript drop down using selenium?

Here is the HTML code for a JavaScript drop-down menu that contains various options, including "All Resumes". I am attempting to select this option using Selenium WebDriver: <div id="resume_freshness_container"> <div class="dropdown_small_wrapper ...

Diminishing sheets in the realm of C# web application development

I have been researching ways to incorporate a fading page function, but I am encountering some issues. I am unsure about the specific code that needs to be included in jquery.js and how to integrate this script into all of my web forms or alternatively int ...

What is the best method for inserting content into a custom element as input for the component?

Currently, I am in the process of creating a syntax highlighting web component that will be able to highlight any content placed inside it. Let me illustrate with an example code snippet: <fs-highlight data-line-numbers="true" data-language=&q ...

How to use Python and JavaScript to make a WebElement visible in Selenium

I am currently facing an issue with uploading a PNG file using Selenium. The input element necessary for the upload process is visible to the user but not to Selenium. Following the suggestions in the Selenium FAQ, I tried using JavaScriptExecutor as shown ...

propagate the previous state using a variable

Currently, I am in the process of refactoring a codebase but have hit a roadblock. My main aim is to update the state when the onChange event of a select box occurs. Specifically, the parameter searchCriteria in my handleFilterChange function is set to in ...

Display Mailchimp subscription form adjacent to button click on a WordPress website

Seeking assistance with integrating a MailChimp simple subscription form (requires email and submit) next to a button on my Wordpress page. The desired functionality is a straightforward button labeled "Newsletter." When clicked, a small form should conve ...

Highlighted option selection in Material UI dropdown using Cypress

Can someone explain how to select Material-UI dropdown options using Cypress? I'm looking for a simple explanation, thanks! ...

Revisiting Cloning Post Knockout Modification

Can anyone provide insight as to why this JSFiddle isn't functioning correctly? My aim is to use an HTML node as a template that updates with Knockout. The initial clone works, but upon updating the model and attempting to clone again, the previous va ...

Unable to suppress error in AngularJS $http.get() call when using catch() method

Below is a simplified version of the code I'm working with, running in CodePen for example: var app = angular.module("httptest", []); app.controller("getjson", ["$scope", "$http", function($scope, $http) { $http.get("https://codepen.io/anon/pen/L ...