A method to apply a class to the third <li> element using javascript

Can someone help me figure out how to add a class to the third element using Javascript? Here is the structure I am working with:

<ul class="products-grid row four-columns first">
<li class="item"></li>
<li class="item"></li>
<li class="item add-class-here"></li>
<li class="item"></li>
</ul>

Answer №2

$(".menu-items li").eq(2).addClass("active");

The above snippet is used to assign a class of "active" to the third list item in the menu. You can apply the eq method in a similar manner for any other element as well.

Answer №3

function activateElement(index) {
    var element = document.querySelector("#Folder_A li:nth-child(" + index + ")");
    //Select nth child under id 'Folder_A'
    element.classList.add("active");
    //Add class 'active' to nth child
}

activateElement(3);
//Alternatively, call the 'activateElement' function onclick
#Folder_A li {
  padding: 12px;
}
.active {
  background-color: green;
}
<ol id="Folder_A">
    <li>FileName 1</li>
    <li>FileName 2</li>
    <li>FileName 3</li>
</ol>

Answer №4

You have the ability to achieve this using vanilla JavaScript.

const elements = document.getElementsByClassName('element');
elements[2].className += " new-class";

A more concise approach that I prefer:

document.getElementsByClassName('element')[2].className += " new-class";

Here is a functional demonstration: https://jsfiddle.net/o98bae4l/


Since you mentioned CSS, there are also CSS selectors available for accomplishing this task solely through CSS styles.

li.element:nth-child(3){
  background-color: yellow;
}

Resource: http://www.w3schools.com/cssref/sel_nth-child.asp

Answer №5

Experiment with the eq() method and apply a class to the third li element using the following code snippet:

$('ul.products-grid > li:eq(2)').addClass('classname')

$('ul.products-grid > li.item:eq(2)').addClass('myclass')
.myclass {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="products-grid row four-columns first">
  <li class="item">item</li>
  <li class="item">item</li>
  <li class="item add-class-here">item</li>
  <li class="item">item</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

How can I transfer data to a different component in Angular 11 that is not directly related?

Within the home component, there is a line that reads ...<app-root [message]="hii"> which opens the app-root component. The app-root component has an @input and {{message}} in the HTML is functioning properly. However, instead of opening t ...

Unleash the power of jQuery by incorporating the Ajax functionality with a hover option to enhance user interactivity. Utilize the .ajax

On my website, I have a calendar displayed with dates like "11/29/2014" stored in an attribute called "data-date". The goal is to check the server for a log file corresponding to that date and change the CSS of the div on mouse hover. Here is the current ...

Troubleshooting SDK Integration with Axeptio in Nuxt3

I am currently developing a Nuxt3 project and I'm looking to integrate a script provided by Axeptio, a cookie platform. To achieve this integration, I created a custom plugin in Nuxt3. export default defineNuxtPlugin((useNuxtApp) => { ;(<any ...

Update the page when the React route changes

I am facing an issue with a function in a component that is supposed to load certain variables when the page is fully loaded. Interestingly, it works perfectly fine when manually reloading the page. However, if I use a NavLink to navigate to the page, the ...

Engaging with the CSS content attribute

Below is a code snippet that inserts an image before the header tag. Is there a way to incorporate JavaScript or jQuery in order to execute certain actions when the inserted image is clicked? h1::before { content: url(smiley.gif); } The HTML code fo ...

Revolutionary Knockout-Kendo MultiSelect Feature: Pressing Enter Erases Previously Selected Options

When using the Knockout-Kendo MultiSelect control, I have encountered an issue. If I select a value from the list, then enter a second value and press enter, the previously entered values are removed. VIEW <select data-bind="kendoMultiSelect: { da ...

The browser's window.location.href fails to redirect the page

Here are my functions: <a onClick="check_claims(this)" type="button" href="javascript:void(0)" redirurl="www.facebook.com" >Invite</a> function check_claims(ele){ var select_claims = document.getE ...

Utilizing Node.Js for Asynchronous Operations

I have a situation in my code where the Process1() function contains a database loop, causing Process2() and Process3() to be called multiple times. Which function from async should I use to properly wait for a for loop? async.waterfall([ function(ca ...

What causes the scope to shift when incorporating a Lazy function within the module pattern in JavaScript?

Implementation 1: Working code in normal var foo1 = function() { var t1 = new Date(); console.log("initialize - one time only " + this); foo1 = function() { console.log("Executes every time after initializing (initialize should not e ...

Need help aligning content with flexbox? Having trouble with align-content and justify-content not working correctly?

First and foremost, I want to express my gratitude in advance for any assistance you can provide. My goal was to neatly align three pieces of content within each row, similar to the image displayed here: https://i.sstatic.net/vtsRj.png To achieve this lay ...

Avoid sudden page movements when validating user input

After successfully implementing the "Stars rating" feature from https://codepen.io/462960/pen/WZXEWd, I noticed that the page abruptly jumps up after each click. Determined to find a solution, I attempted the following: const labels = document.querySelect ...

Leveraging a JavaScript variable within a PHP snippet

Similar Question: Sending a PHP string to a JavaScript variable with escaped newlines Retrieving a JavaScript variable from PHP I am trying to work with a Javascript function that accepts one variable, having some PHP code embedded within it. I am ...

Utilizing PHP and Ajax for paginating JSON responses

I have successfully parsed some JSON data from the YouTube API, but I am running into a limitation where only 50 results can be shown per request. I am looking for help on how to implement pagination using either JavaScript or Ajax in my PHP script. The go ...

Scrollbar not displaying on IE when set to overflow: auto

Greetings, all! I am facing yet another design challenge with Internet Explorer. I have a DIV with Overflow:auto on my website that works perfectly fine on Chrome. However, when it comes to IE, the scroll bar doesn't show up and all the images inside ...

JavaScript can be used to activate the onclick event

Is there a way to disable and then re-enable all buttons that share the same class name? I attempted the following code without success: let buttons = document.getElementsByClassName("btn-st"); for (let i = 0; i < buttons.length; i++) { b ...

Issue: "StoreController Undefined" error in Python Flask + Angular application

In the python flask application that I have built with Angular JS for the front end, there are three main files. app.py import json import flask import numpy as np app = flask.Flask(__name__) @app.route("/") def index(): ...

Bidirectional enumeration in TypeScript

I am working with an enum defined as: enum MyEnum { key1 = 'val1' key2 = 'val2' } However, I am unsure how to create a SomeType implementation that fulfills the following requirements: Function: const myFunction = (param: SomeT ...

Tackling JavaScript: Exploring Ternary Short Circuit and If Short Circuit

I am attempting to optimize the code by using a ternary operator to quickly return false. My understanding was that using a ternary in this scenario would have the same outcome as the if statement below it, which is to instantly return false if the lengths ...

The inability of Chrome and Firefox browsers to open Windows folders directly from a hyperlink is a common

My link is directing to a Windows folder using its directory path. Surprisingly, it works perfectly fine in Internet Explorer but fails to work in Chrome and Firefox. How can I resolve this issue? The structure of my link looks like this: <a href="&bs ...

Karma, Webpack, and AngularJS are successfully passing all tests, yet encountering karma errors with an exit code of 1

Currently running karma 4.0.1, webpack 4.31.0, angular 1.6.8, karma-jasmine 2.0.1, jasmine-core 3.4.0 Recently at my workplace, I transitioned our angularjs application from a traditional gulp build process to webpack + es6. The journey has been smooth wi ...