Include a new class in the classList of an element at a specific index

Is it possible to add a class to a specific position in order to maintain a certain order, especially when it goes against the logic that targets the class based on its position?

link.closest('item').classList.add('c-class')

// Contradiction We need (a-class) instead I get (c-class) that has been added
let getThisClass = e.target.parentElement.classList[1]
<!-- before adding -->
<li class="item aclass bclass" id="60fe102d6e87274484dd2785"></li>
<!-- after adding -->
<li class="item c-class a-class b-class" id="60fe102d6e87274484dd2785"></li>

Answer №1

To insert a new class into the className, you can split it by spaces, add the new class at a specific position in the array (using Array#splice), and then reassign the updated className back after joining by spaces:

const link = document.getElementById("60fe102d6e87274484dd2785");
list = link.className.split(" ");
list.splice(1, 0, "c-class")
link.className = list.join(" ");
console.log(link.className);
<!-- before adding -->
<li class="item aclass bclass" id="60fe102d6e87274484dd2785"></li>

For a more general implementation, you can use the following function:

const link = document.getElementById("60fe102d6e87274484dd2785");
insertClassAtPosition(link, "c-class", 1);
console.log(link.className);

function insertClassAtPosition(element, className, index){
  let l = element.className.split(" ");
  l.splice(index, 0, className);
  element.className = l.join(" ");
}
<!-- before adding -->
<li class="item aclass bclass" id="60fe102d6e87274484dd2785"></li>

Answer №2

// selecting the link element
const link = document.getElementById("link");

// finding the closest item element
const item = link.closest('.item');

// adding a new class to the item element
item.className += ' c-class';
console.log(item.className);

// removing the added class from the item element
item.className = item.className.replace(/c-class/,'').trim();
console.log(item.className);
<!-- original structure -->
<li class="item a-class b-class" id="60fe102d6e87274484dd2785"><a id="link">#</a></li>

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 Javascript, verify if a given URL is legitimate and commences with "http://" or "https://"

I need to validate the authenticity of my URLs, ensuring they begin with either http:// or https://. Here is the regular expression (RegExp) I have been using: private testIfValidURL(str) { const pattern = new RegExp('^(https?:\\/&bsol ...

Disable the background color css when hovering over a button

I'm having trouble with my Angular and HTML code. https://i.stack.imgur.com/Ea5oV.png The image above shows that a background color appears when hovering over the first icon. I've attempted: .sidemenuitm { padding: 10px 5px; cursor: poin ...

Obtaining a list of child span elements using xpath in Selenium

I am looking to retrieve all child span elements based on the following xpath //label[@for='someText']/span Expected result: <span class="someClass">"Find this text"</span> <span id="someId">" ...

Is it necessary to have NodeJs in order to host a React app on a server?

I've been working on a .NET Core 2.2 project with React integration, As I'm nearing completion of the project, I have a query that has been on my mind. Do I need Node.js installed on the server for React to function properly? Thank you. ...

List that spans the entire width of the browser, with text limited to a maximum width

I've encountered an issue with a full-width list in my browser. It has a background color that changes when hovered over. However, I want the text within each li element to have left-aligned alignment, a maximum width, and equal left and right margins ...

Using two different colors in text with CSS

Is it possible to have text in two different colors like this: https://i.stack.imgur.com/R40W1.png In terms of HTML, I tried looking it up but found answers related to:- https://i.stack.imgur.com/GRAfI.png ...

Implementing Placeholder Text Across Multiple Lines with Material UI

Currently, for the React App I am developing, I am utilizing Material UI. In order to achieve a multi-line placeholder for a textarea using the TextField component, here is what I have so far: <TextField id="details" ful ...

What steps can be taken to execute a function when a button remains unclicked?

$("#RunCode").click(function(){ var $this = $(this); if($this.data('clicked')) { console.log("Is clicked"); $(".documentWrite").text("Is clicked"); } else { $this.data('clicked', true); consol ...

How to Validate Prop Types in VueJS When Dealing With NULL and 'undefined' Values?

Despite what the official VueJS 2 documentation on prop validation says in a code example comment: // Basic type check (null and undefined values will pass any type validation) I encountered an error while testing this piece of code — could you explai ...

What is the best way to enhance specific sections of Django content by incorporating <span> tags, while maintaining the original paragraph text format?

I am currently in the process of trying to showcase a paragraph of text (content) from django. However, my aim is to incorporate <span class="modify"> into particular words that match pre-defined words located within a referenceList within the paragr ...

Protractor - selecting a hyperlink from a list

Imagine you have a todo application with tasks listed as follows: Walk the dog, Eat lunch, Go shopping. Each task has an associated 'complete' link. If you are using Protractor, how can you click on the 'complete' link for the second t ...

Enhancing Next.js Images with Custom CSS Styles

I am working with a Next.js component: import styles from '../styles/Navbar.module.css' import Image from 'next/image' export const Navbar = () => { <div> <Image className={styles["navbar-home-icon"]} ...

What causes scope to be undefined in Angular?

Using ionic to develop a hybrid app has been a smooth experience, especially with android! This is my login HTML: <body ng-app="starter"> <head> <script src="phonegap.js"></script> </head> <ion-header-ba ...

Placing a div with absolute positioning inside another div with absolute positioning raises the question of how it functions when the outer div is not set to position: relative

Trying to grasp the concept, I experimented with the following setup: <div id="Outer"> <div id="Inner"></div> </div> In this scenario, the outer div has a relative position and the inner div has an absolute position. This allo ...

Trouble with selecting inputs within a Div Element

Could you please review the code below and help me understand why I am unable to retrieve the ID of the selected radio buttons using this.id? <div id="pay" class="btn-group" data-toggle="buttons"> <label class="btn btn-primary"> < ...

Guide to redirecting on click when utilizing an iframe

I needed to prevent the page from reloading before the action was complete by using an iframe. However, I encountered an issue where I needed the page to refresh after the action took place. I attempted two methods to achieve this - refreshing the page and ...

Troubleshooting a problem with CSS animations disappearing

I've been experimenting with CSS animations and I've run into a bit of a snag. I'm looking to create a div that fades in with a delay - meaning it won't be visible until the animation starts. Here's what I have so far: http://jsfi ...

What could be causing my Font Awesome icon background to fail to load?

As a newcomer to website design, I am currently learning CSS. I seem to be facing an issue where the background for the first two icons has loaded successfully, but the second one isn't displaying. .bg-instagram { padding: 7px 10px; border-radi ...

Ensure that the image inside a resizable container maintains the correct aspect ratio

I often encounter a situation where I need to showcase a series of thumbnails/images that adhere to a specific aspect ratio within a flexible container. My current approach involves using a transparent, relatively positioned image to enforce the correct as ...

Simple Steps to Connect an HTML File to CSS in Windows Notepad

I have scoured the depths of the online realm in search of a method to connect HTML with CSS within the preinstalled Notepad application on Windows. Regrettably, my attempts, including utilizing the system path, proved fruitless. Is it conceivable to ach ...