Apply the Class to each alternate element starting from the first one

I have a task to assign specific classes to every other element in a list, starting from the first one.

Check out the list below:

<ul class="timeline">
  <span class="topbullet"></span>
  <li></li>
  <li></li>
  <div class="clearfix"></div>
  <li></li>
  <li></li>
  <div class="clearfix"></div>
  <li></li>
  <li></li>
  <div class="clearfix"></div>
  <li></li>
  <li></li>
  <div class="clearfix"></div>
  <li></li>
  <li></li>
  <div class="clearfix"></div>
</ul>

The desired output is as follows:

<ul class="timeline">
  <span class="topbullet"></span>
  <li class="odd"></li>
  <li class="even"></li>
  <div class="clearfix"></div>
  <li class="odd"></li>
  <li class="even"></li>
  <div class="clearfix"></div>
  <li class="odd"></li>
  <li class="even"></li>
  <div class="clearfix"></div>
  <li class="odd"></li>
  <li class="even"></li>
  <div class="clearfix"></div>
  <li class="odd"></li>
  <li class="even"></li>
  <div class="clearfix"></div>
</ul>

Here's the jQuery code I'm using:

$(".timeline li:nth-of-type(2n)").addClass('even');

While adding the 'even' classes is easy, I'm not sure how to add the 'odd' classes. Can anyone suggest the right selector to achieve this starting from the first list item?

Answer №1

If you're looking to alternate the styling of elements using jQuery, you can achieve this by utilizing the odd and even selectors as shown below:

$( ".timeline li:odd" ).addClass('odd');
$( ".timeline li:even" ).addClass('even');

To switch the order of applying odd and even styles based on your specific requirements, you can modify the jQuery code like so:

$( ".timeline li:odd" ).addClass('even');
$( ".timeline li:even" ).addClass('odd');

Answer №2

Perhaps only this

const elements = document.body.querySelectorAll(".timeline li");
elements.forEach(function(item,index){
   item.classList.add(index % 2?"even":"odd");
})

Answer №3

Make sure to include the prev() method in your code:

$(".timeline li:nth-of-type(2n)").addClass('even').prev().addClass('odd');
.even{
  color:red;
}
.odd{
  color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="timeline">
  <span class="topbullet">Span</span>
  <li>Li</li>
  <li>Li</li>
  <div class="clearfix">Div</div>
  <li>Li</li>
  <li>Li</li>
  <div class="clearfix">Div</div>
  <li>Li</li>
  <li>Li</li>
  <div class="clearfix">Div</div>
  <li>Li</li>
  <li>Li</li>
  <div class="clearfix">Div</div>
  <li>Li</li>
  <li>Li</li>
  <div class="clearfix">Div</div>
</ul>

Answer №4

One way to accomplish this could be to loop through the elements that match the selector ".timeline li" and assign a specific class based on whether their index is even or odd.

$(".timeline li").each((index, element) => $(element).addClass(index % 2 ? 'even' : 'odd'));

Answer №5

Amend the following code snippet:

$(".timeline li:nth-of-type(2n)").addClass('even');

to this revised version:

$(".timeline li:nth-child(even)").addClass('even');

Answer №6

To apply a specific style to elements, simply use CSS selectors

.list-items li:nth-of-type(odd) {
    background: red;
}
.list-items li:nth-of-type(even) {
    background: blue;
}

Answer №7

To differentiate odd and even elements in a list, you can use the following code snippet.

$(document).ready(function() {
  $('ul.listul li:even').addClass('even');
  $('ul.listul li:odd').addClass('odd');
});
li.even {
  color: #000;
}

li.odd {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="listul">
  <li>list1</li>
  <li>list2</li>
  <li>list3</li>
  <li>list4</li>
  <li>list5</li>
  <li>list6</li>
</ul>

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

Using navigateByUrl() to pass a query parameter

When I click on an icon, I want to navigate to a new page. Here's the code snippet: this.prj = e.data.project_number; this.router.navigateByUrl('/dashboard/ProjectShipment/634'); Instead of hardcoding the query parameter 000634, I need ...

Understanding the concept of for loops in JavaScript and incorporating them in CSS styling

Hello there! I initially used this code to draw 12 lines, but now I am looking to incorporate a for loop and implement it in CSS. Can someone please guide me on how to proceed? <!DOCTYPE html> <html> <head> <style> #straigh ...

Clicking a button with Java Selenium

While trying to navigate all the pages on a website, I encountered an issue where after scrolling to the second page, I received an exception stating that the element does not exist on the page. Upon further investigation, I realized that the CSS selecto ...

Guide on extracting part of a string in JavaScript from a specific starting point to a designated character

Currently working on a JavaScript project where I am in need of extracting words enclosed within two brackets. For example: [Green]- Amazon I specifically require the word "Green" from within the brackets. Using indexOf() won't work as there could ...

Exploring the functionality of test code within an rxjs subscription by utilizing the powerful technique of jasmine

My goal is to test the code within an observable subscription: function bar(someStream$: Observable<number>) { someStream$.pipe( map((x) => x + 3), ).subscribe((result) => { SomeService.someMethod(result) }) } I want to ensure t ...

What is the purpose of enveloping the BrowserRouter in a parent component as opposed to the routes child component for react router v6?

Attempting to implement the useRoutes hook from [email protected] for creating App routes in JavaScript, I organized my code as follows in routes.jsx: import { useRoutes } from "react-router-dom"; import TestPage from "../Pages/Public/T ...

Vue triggering axios on every dropdown selection made

I have a Vue template that currently calls a method (axios call) upon page load, which works well. However, I would like to modify it so that whenever I select an option from the dropdown menu, it will re-call the axios method with the selected option. S ...

Text included in the body of an email sent through Outlook

Whenever I click on a specific button, it opens Outlook with the provided details. Additionally, there is a TEXTAREA element containing certain texts. Is there a way to display this text in the body of my Outlook email? Below is the sample code - & ...

A pair of vertical sliders

I am currently troubleshooting a website located at . It seems that there are two vertical scroll bars appearing on both the home page and product page, such as here: Interestingly, these extra scroll bars do not appear on the category page located here: ...

Utilizing the LinkedIn API: Posting a network update using a variable value

Currently, I have a string variable and I am looking to post the value stored in this variable as a network update on LinkedIn. Could someone please provide guidance on how I can modify the code below to make this functionality possible? updateURL = "/pe ...

One Page HTML5 with a Bootstrap fixed top menu, revealing content on menu item click

Is there a way to have the Bootsrap mobile menu automatically unfold when a link (anchor on the same page) is clicked? The menu unfolds with class navbar-collapse collapse in The menu folds with class navbar-collapse collapse out I already have an oncl ...

Using AngularJS to send data from a controller to a factory

Looking to implement a basic pagination feature with data from the backend. Each page should display 10 activities. /feed/1 -> displays 0-10 /feed/2 -> displays 10-20 /feed/3 -> displays 20-30 The goal is to start at page 1 and increment the pag ...

The React/Redux bundle.js file is overly large and bloated

I am currently working on a React project, and the bundle.js file generated by Webpack is quite large at 6.3Mb. I am looking for ways to reduce this size to less than 2.0Mb (though 2Mb would still be acceptable). The full source code can be found on Github ...

Adding a new item to a collection by pushing it onto an array using the

Currently, I am attempting to modify a collection by adding elements to an existing array within the collection. Below is the function I am trying to execute for updating: Games.update({ _id: game._id }, { $push: { players: { name: playerName } }, }); ...

How to implement AJAX pagination in Select2 version 4

Is there a way to paginate results (every 25 rows) using Select2 4.0? I'm not sure how to achieve this. Any suggestions? If the user reaches the end of the initial 25 rows and there are more rows available, I would like to load and display them. Bel ...

Loop through each item in an array

Currently, I am leveraging vue.js and lodash to iterate through a list of events in order to extract the promoted events. My goal is to then store each event in a new object or array that holds a refined list of promoted events. However, instead of conso ...

Could someone explain to me why searchQuery.value is coming up as undefined?

Within my development task, I am endeavoring to create a functional search icon on the header bar that allows users to input Pokémon names for searching purposes. Despite my efforts, I am consistently facing a console error message suggesting "searchQu ...

What is the best way to connect a text box to a nested object in the state of a React component?

Solving a React Debugging Dilemma In my current project, I'm developing an office add-in using a React-based starter kit and TypeScript. Unfortunately, debugging has been a challenge as I am unable to access detailed error messages from React in my s ...

Updating a MySQL field based on checkbox status changes can be achieved by utilizing jQuery (Ajax), PHP, and MySQL

I'm just learning about jquery and ajax, and I'm struggling with a specific task... On my PHP webpage, I have a table that displays data from a MySQL database. Each row represents a "message" and the last column is a boolean field called "read" ...

Launching a Node.js Express application on Heroku

I'm facing an issue while trying to deploy my app on Heroku, as I keep encountering the following error: 2022-08-11T12:49:12.131468+00:00 app[web.1]: Error: connect ECONNREFUSED 127.0.0.1:3306 2022-08-11T12:49:12.131469+00:00 app[web.1]: at TCPConnect ...