When using classList.replace, it should swap out every instance of the class xxx1yyy with xx

I attempted to swap a class and came across this helpful example here: javascript: replace classList that is inside a conditional

Unfortunately, my attempt at modification (shown below) did not work.

The use of classList.replace should change all instances of the class xxx1yyy to xxxyyy

This means I want to replace classes like my1bla, mu1bla, my1hu, …1… and so on with mybla, mubla, myhu, …

<!DOCTYPE html>
<html>
<style>
.my1bla {
background-color: black;
}
.mybla {
background-color: blue;
}
</style>
<p>Click button to change b style class from DIV. background-color will change from black to blue (hopefully)</p>

<button onclick="myFunction()">Try it</button>

<div id="myDIV" class="my1bla">
I am a DIV element
</div>

<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.classList.contains("1")) {
    x.classList.replace("1", "");
} else if (x.classList.contains("1")) {
    x.classList.replace("1", "");
}
}
</script>

Answer №1

Give this a shot:

function updateClass() {
  var element = document.getElementById("targetElement");

  element.classList.value = element.classList.value.replace("oldClass", "newClass");
}

https://example.com/code-sample-link

Answer №2

You cannot alter it with just one word. .contains will output true or false & .replace will substitute the entire className

<!DOCTYPE html>
<html>
<style>
  .my1bla {
    background-color: black;
  }
  
  .mybla {
    background-color: blue;
  }
</style>
<p>Click button to change b style class from DIV. background-color will change from black to blue (hopefully)</p>

<button onclick="myFunction()">Try it</button>

<div id="myDIV" class="my1bla">
  I am a DIV element
</div>

<script>
  function myFunction() {
    var x = document.getElementById("myDIV");
    if (x.classList.contains("my1bla")) {
      x.classList.replace("my1bla", "mybla");
    } else if (x.classList.contains("my1bla")) {
      x.classList.replace("my1bla", "mybla");
    }
  }
</script>

Answer №3

You have the option to utilize the Element.classList.toggle method.

function toggleStyle() {
  const element = document.getElementById("myDIV")

  element.classList.toggle('style1')
  element.classList.toggle('style2')
}
.style1 {
  background-color: black;
}

.style2 {
  background-color: blue;
}
<p>Click on the button to change the style class of the DIV element. The background-color will transition from black to blue (hopefully).</p>

<button onclick="toggleStyle()">Try it</button>

<div id="myDIV" class="style1">
  I am a DIV element
</div>

<script>
</script>

Answer №4

Utilizing data attributes is a simple way to achieve this task. By modifying the string within the data-class attribute and then resetting it as dataset, you can effectively change the class of elements.

const button = document.querySelector("button");
const boxes = document.querySelectorAll(".box");
let initial = true;
const checkClasses = () => {
  boxes.forEach(box => {
    let dataClass = box.dataset.class;
    if (initial) {
      let dataClass = box.dataset.class.split("1").join("");
      box.setAttribute('data-class', dataClass);
    }
  });
}
button.addEventListener("click", checkClasses);
body {
  margin: 0;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

div {
  height: 100px;
}

[data-class="my1blue"] {
  background: royalblue;
}

[data-class="myblue"] {
  background: blue;
}

[data-class="my1red"] {
  background: tomato;
}

[data-class="myred"] {
  background: red;
}

[data-class="my1green"] {
  background: olive;
}

[data-class="mygreen"] {
  background: green;
}

button {
  margin: 1rem;
}
<div data-class="my1blue" class="box"></div>
<div data-class="my1red" class="box"></div>
<div data-class="my1green" class="box"></div>

<button>click me</button>

Answer №5

If you always know the value will be 1, you can utilize a contains selector to avoid looping through each element in the DOM

document.querySelectorAll("[class*='1']").forEach(elem => elem.classList.value = elem.classList.value.replace(/1/, ''));
.my1bla {
  background-color: black;
}

.mybla {
  background-color: blue;
}
<div id="myDIV" class="my1bla">
  I am a DIV element
</div>

<div id="myDIV" class="my1bla">
  I am a DIV element
</div>

<div id="myDIV" class="my1bla">
  I am a DIV element
</div>

<div id="myDIV" class="my1bla">
  I am a DIV element
</div>

<div id="myDIV" class="my1bla">
  I am a DIV element
</div>

Answer №6

After reviewing the responses beforehand, I was able to devise a comprehensive solution that addresses the issue at hand:

<style>
.my1bla {
background-color: black;
}
.mybla {
background-color: blue;
}
</style>

<button onclick="myFunction()">Modify style class within DIV</button>
<div class="my1bla">This is a DIV element</div>

<script>
function myFunction() {
  var elems = document.body.getElementsByTagName("*");
for (i in elems) {
    ele = elems[i];
    if(ele.classList)
        ele.classList.value = ele.classList.value.replace("1", "");
};
}
</script>

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

Is there a more efficient approach to applying a basic function to multiple elements within a DIV and having it activate only upon a click event using jQuery?

This solution works, but I am looking for a more professional approach in order to adhere to the principle of "don't repeat yourself." $("document").ready(function(){ $(".child").each(function(index){ $(this).click(func ...

Utilize the power of jQuery to make an ajax request to a PHP backend, expecting a response in JSON format. Then,

Having some trouble with my jQuery code when trying to parse a JSON object returned by PHP and create a list of hyperlinks. Despite receiving the JSON object, my list turns out empty. Can anyone assist me? Below is the jQuery code snippet and the JSON resp ...

Error TS2322: Type 'boolean' cannot be assigned to type 'undefined'. What is the best approach for dynamically assigning optional properties?

I am currently working on defining an interface named ParsedArguments to assign properties to an object, and here is what it looks like: import {Rules} from "../Rules/types/Rules"; export interface ParsedArguments { //other props //... ...

The drop-down menu does not maintain its selected option after the window is refreshed

I am struggling with a dropdown list as shown below: <select class="span2" id ="sort" name= "order_by"> <option >Default</option> <option >Price</option> <option >Color</option> ...

Unknown custom element error in Laravel and Vuetify

I encountered errors in my Laravel project, specifically with custom elements like this. [Vue warn]: Unknown custom element: <v-app> - did you register the component correctly? For recursive components, make sure to provide the "name" option. found ...

Combining HashRouter and anchor navigation in React: A guide to seamless page navigation

I am currently utilizing the HashRouter functionality from the library react-router-dom. The issue I am facing is when attempting to link to a specific div on the same page using an anchor tag: <a href="#div-id"> Link to div </a> In ...

Checking with jQuery Validate: displaying an error message if input matches a certain value

I spent 6 hours trying to figure out a solution to my issue. Currently, I am utilizing the jQuery Validation plugin. In my form, there is a password input field. When an AJAX request detects an incorrect password, another input field is set to a value of ...

Changing the background color completely

Need help with CSS! I have two divs, one with a background color of #000 and the other with a transparent PNG image as the background. I want to override the background color with transparency from the PNG file so that the background doesn't cover th ...

Condensed JQuery condition code for "if" statement

This piece of code is designed to sequentially display 10 questions and control the visibility of each question using the CSS class .hideme. It also sends metrics data to Google Analytics. Although it functions properly, I feel like the code is too leng ...

Incorporate a horizontally rotating preloader to enhance loading experience

I am currently in the process of developing a preloader that rotates an image horizontally. After researching different threads and ideas, I came across a solution that looks something like this: <style> .imageRotateHorizontal{ -moz-anima ...

I'm looking for a solution to implement a vertical carousel in Google's Materialize CSS without the need for custom development

Looking to create a unique vertical scrolling "carousel" using Google's Materialize CSS library. I have a good understanding of the steps required to construct a carousel. # haml %ul.carousel %li.carousel-item Some Content %li.carousel-item ...

Guide on how to save the selected user option in a PHP form

I'm having trouble getting the form to automatically set itself based on the state selected by the user from a drop-down menu of 50 states. The user's info, including their chosen state, is stored in an info array with $state. Everything else dis ...

Leverage Html5 to open and retrieve data from an Excel document

Is there a method to access excel file data using HTML5 while uploading the file on the client side? I have come across the use of reader in JavaScript, but unsure how it can be helpful in this scenario. Is there a way to read excel file data seamlessly ...

Tips for centering the second content within a div block

<div style="height: 100%; background: red"> <div style="height: 100px; background: green"> </div> <div style="background: blue;"> <h1>Content</h1> </div> </di ...

Modify HTML content according to the response received from the backend

I am trying to dynamically update the text content of an HTML tag based on a response from the backend. My application is running on a Django server where I have a timer in the backend measuring the processing time. I need to send this processing time to t ...

Is it possible to apply a class without using ng-class?

Seeking a more efficient way to apply conditional classes to multiple elements on a validation form page, I am exploring options to assign one of five potential classes to each form input. While the traditional method involves manually specifying the class ...

Displaying Real-Time Values in ReactJS

Hi there, I am currently using the code below to upload images to Cloudinary: import React, { Component } from 'react'; import './App.css'; import Dropzone from 'react-dropzone'; import axios from 'axios'; const F ...

Utilize Selenium with Eclipse (Java) to validate the CSS table border style

I'm currently conducting a form test that involves leaving mandatory fields empty to verify if the field displays a red border indicating it needs to be filled before proceeding. Below is the code snippet I have implemented so far: driver=new Firefox ...

What is the best way to reposition the main body content lower on the page when switching to mobile layout?

I am facing an issue where my website switches to mobile design at 850px, but the button I have on both desktop and mobile mode gets hidden under the header banner when it transitions to mobile design. I want to adjust the main body content of the website ...

The table fails to refresh after adding, modifying, or removing a row

Incorporating ReactJs with Material-UI, I am working on displaying a table of Car components where the display does not update after any Create, Edit, or Delete action has been performed. Below is the structure: class MainCar extends React.Component { c ...