Guide to modifying CSS properties of an individual element by manipulating class names with JavaScript

I have been searching for an answer to my question without success. I have a unique challenge where I need to change the styles of an h1 element by adding a class based on which radio button is clicked. The issue I'm facing is that when I select a different button, the new class is added but the previous classes remain. I resorted to a brute force solution, but I know there must be a better way to achieve this with more dynamic styling options.

To see the attempt and code in action, visit: https://jsfiddle.net/ebzjknqo/4/

HTML CODE

const button = document.forms.namedItem('color');

const changeColor = (color) => {
  const title = document.querySelector('#title');

  title.classList.add(`title-${color}`);
  console.log('classlist: ', title.classList);

  title.innerHTML = `i am ${color}`;
};

button.addEventListener('change', (e) => changeColor(e.target.value));
#title {
  margin: 0.5em auto;
  text-align: center;
  text-transform: capitalize;
}

/* RADIO BUTTONS */
#button-group {
  text-align: center;
}

#button-group label {
  font-size: 0.8rem;
  border: rgb(117, 114, 114) solid 1px;
  background-color: rgb(236, 236, 236);
  border-radius: 4px;
  text-transform: uppercase;
  padding: 0.7em 1.5em;
}

#button-group input[type='radio'] {
  opacity: 0;
  z-index: 100;
  width: 0;
  display: none;
}

#button-group label:hover {
  background-color: rgb(199, 199, 199);
  cursor: pointer;
}

.btn {
  padding: 0.5em 1.5em;
  margin: 1em auto;
}

.title-blue {
  color: blue;
}

.title-red {
  color: red;
}

.title-orange {
  color: orange;
}
<section class="main">
  <h1 id="title">Hello World</h1>
  <div id="button-group">
    <form name="color">
      <input
        type="radio"
        id="btn-red"
        name="btn"
        value="red"
        onchange="changeColor(this.value)"
      />
      <label for="btn-red">Red</label>
      <input
        type="radio"
        id="blue"
        name="btn"
        value="blue"
        onchange="changeColor(this.value)"
      />
      <label for="blue">Blue</label>
     <input
        type="radio"
        id="orange"
        name="btn"
        value="orange"
        onchange="changeColor(this.value)"
      />
      <label for="orange">Orange</label>
    </form>
  </div>
</section>

Answer №1

To remove classes from an element, you can utilize the className property.

const button = document.forms.namedItem('color');

const changeColor = (color) => {
  const title = document.querySelector('#title');
  title.className = '';
  title.classList.add(`title-${color}`);
  title.innerHTML = `i am ${color}`;
};

button.addEventListener('change', (e) => changeColor(e.target.value));
#title {
  margin: 0.5em auto;
  text-align: center;
  text-transform: capitalize;
}

/* RADIO BUTTONS */
#button-group {
  text-align: center;
}

#button-group label {
  font-size: 0.8rem;
  border: rgb(117, 114, 114) solid 1px;
  background-color: rgb(236, 236, 236);
  border-radius: 4px;
  text-transform: uppercase;
  padding: 0.7em 1.5em;
}

#button-group input[type='radio'] {
  opacity: 0;
  z-index: 100;
  width: 0;
  display: none;
}

#button-group label:hover {
  background-color: rgb(199, 199, 199);
  cursor: pointer;
}

.btn {
  padding: 0.5em 1.5em;
  margin: 1em auto;
}

.title-blue {
  color: blue;
}

.title-red {
  color: red;
}

.title-orange {
  color: orange;
}
<section class="main">
  <h1 id="title">Hello World</h1>
  <div id="button-group">
    <form name="color">
      <input
        type="radio"
        id="btn-red"
        name="btn"
        value="red"
        onchange="changeColor(this.value)"
      />
      <label for="btn-red">Red</label>
      <input
        type="radio"
        id="blue"
        name="btn"
        value="blue"
        onchange="changeColor(this.value)"
      />
      <label for="blue">Blue</label>
     <input
        type="radio"
        id="orange"
        name="btn"
        value="orange"
        onchange="changeColor(this.value)"
      />
      <label for="orange">Orange</label>
    </form>
  </div>
</section>

Answer №2

In the world of HTML5, there are built-in functions that allow you to easily add or remove CSS class attributes.

document.getElementById("MyElement").classList.add('MyClass');

document.getElementById("MyElement").classList.remove('MyClass');

if ( document.getElementById("MyElement").classList.contains('MyClass') ) 

document.getElementById("MyElement").classList.toggle('MyClass');

Answer №3

Utilize the ternary operator and modify it according to your preferred condition

a ? true:false;

classname={"existingclassnames "+condition ? "classname1":"classname2"};

Note: Remember to include a space after existingclassnames

Correct way: existingclassnames classname1(or)2 depending on your condition

Incorrect way: existingclassnamesclassname1(or)2 based on your condition

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

Code snippet for calculating the size of an HTML page using JavaScript/jQuery

Does anyone know of a way to calculate and display the size/weight (in KB) of an HTML page, similar to what is done here: Page size: 403.86KB This would include all resources such as text, images, and scripts. I came across a Pelican plugin that does th ...

Collapsing one tab when another is selected in the accordion interface

I have successfully implemented an accordion feature, but I am facing an issue where the tabs do not close when another one is clicked. Currently, they only open but fail to close the previously opened tab... Below is the code snippet for reference: < ...

The table borders in IE 11 do not display properly when using Html5 and CSS

In a previous version, the table had visible borders. However, when I added the property text-align:center; to my container, the table did not align to the center. I then tried adding display:inline-block; to the table, which successfully centered it. It l ...

Incorporating unique typography onto your website (HTML/CSS)

I am currently struggling to implement a custom font on my website. I'm not very experienced with programming, and since my friend isn't available to help, I'd appreciate a solution from anyone. The issue I'm facing is that while the Ca ...

Step-by-step guide on bypassing Content Security Policy with JavaScript

I have Content Security Policy enabled for security purposes in my current project, but I need to disable it for certain JavaScript files. Can this be done? I am trying to make API calls from my JavaScript files in order to retrieve results. ...

Adjust padding of radio button labels in Qualtrics for a cleaner, more streamlined appearance

As I delve into the world of CSS, my goal is to customize the existing survey theme known as "Minimal 2014". Specifically, my focus is on minimizing the spacing in various areas to create a more compact design. So far, I've successfully reduced the g ...

SASS: incorporating loops within CSS properties

Is there a way to generate multiple values for a single property in CSS? background-image: radial-gradient(circle, $primary 10%, transparent 10%), radial-gradient(circle, $primary 10%, transparent 10%), radial-gradient(circle, $primary 10%, tr ...

Styled-components does not generate a style tag as output

After creating a new project in React with Webpack, I decided to experiment with Styled Components. In my index.js file, the code is structured like this: import React from "react" import ReactDOM from "react-dom" import Page from "./site/Page" import s ...

Varying heights based on the screen size

Currently, I am in the process of designing my website and incorporating some wave elements to enhance the background. However, I've encountered some issues when resizing the screen. Specifically, the waves seem to shift with a space between them as t ...

Error: Unable to locate module 'react-calendar-heatmap'

After successfully creating a component that functioned flawlessly in my local application, I encountered an error when attempting to integrate it with npm: ./src/App.js Module not found: Can't resolve 'heatmap-calendar-react' in 'C:& ...

Adjust the image size to fit the page according to its height

Having a dilemma here. I have this square image (2048x2048) that I want to set as a background. The tricky part is, I want it to display borders when the page stretches into widescreen mode, but also resize while maintaining its square shape when the page ...

The Json parsing failed to deserialize the API response

Struggling to send a JSON to my API, I've tried various solutions but still can't figure out what's going wrong. I'm stuck on this post call function: @PostMapping(path = "ts/sts") public void saveTestStep(@RequestBody Tes ...

When the page is dynamically loaded, Ng-repeat does not function as expected

I am working on a page that includes the following code snippet: <script> angular.module('myapp', []).controller('categoryCtrl', function($scope) { $scope.category = <? echo json_encode($myarr); ?>; $scope.subcatego ...

What's the reason behind the failure of bitwise xor within a JavaScript if statement?

I'm trying to understand the behavior of this code. Can anyone explain it? Link to Code function checkSignsWeird(a,b){ var output = ""; if(a^b < 0){ output = "The "+a+" and "+b+" have DIFFERENT signs."; }else{ output = ...

Running an express server on localhost with nginx: A step-by-step guide

Is it possible to run the express server using Nginx on localhost? And if so, how can this be accomplished? const express = require('express') const app = express() const port = 3000 app.get('/', (req, res) => res.send('Hello ...

Can someone confirm if a user has administrator privileges?

Is it feasible to determine if members of a discord server possess administrator privileges in a looping structure? I am aiming to prohibit individuals who hold a role below my bot in the server that belongs to me and my companions. How can I achieve this? ...

What is the best way to handle code versioning using Django, Angular2, and Webpack?

Currently, I am utilizing Django in conjunction with Angular 2 and Webpack. Within Django, I have set up a URL to display my application at http://example.com/user/beta. Initially, my index.html file is rendered, which contains my Angular 2 components. Wit ...

Unable to verify the provided resource: Mailchimp

Welcome everyone to my first question posted on StackOverflow. I have tried my best to provide all the necessary details regarding the issue in order to seek assistance. If you require additional information, feel free to ask. To give a brief overview, I ...

Transforming strings of HTML into objects in the DocX format

After developing a TypeScript script that transforms a JSON string into a Word Doc poster using Docx, I encountered a hurdle. Certain sections of the JSON may contain HTML tags, such as <br/>, <i>, <p>, and I need a way to pass the stri ...

Success in building with Vue CLI 3 even when encountering lint errors

After setting up a project with Vue CLI 3 rc3 and enabling lintOnSave, I noticed that the linting errors are showing up as warnings during the build process without causing it to fail. Is this the expected behavior? If so, how can I configure it to make ...