Tips for altering the appearance of a header when clicked on?

I am trying to change the internal style sheet in the "style" head when a user clicks, without using inline styles. I have successfully added new CSS for divone as text, but I can't seem to delete the old one (element.classList.remove("#divone");). Is there an idlist.remove method or any other way to achieve this? Any suggestions would be appreciated. Thank you.

<!DOCTYPE html>
<html>
<head>
<style id="style">
#divone{
width: 500px;
height: 50px;
background-color: red;
}
#divtwo{
width: 400px;
height: 80px;
background-color: purple;
}
</style>
</head>
<div id="divone"></div>
<div id="divtwo"></div>
<button onclick="myFunctionTest()">Click me</button>
function myFunctionTest() {
    var element = document.getElementById("style");
    element.classList.remove("#divone");
    document.getElementById("style").textContent += "#divone{width: 400px; height: 35px; background-color: red;}";
}

Answer №1

When attempting to delete a class, avoid using an id

To correct this, replace the id symbol # with the class symbol . and change the DOM id to a class name:

function myFunctionTest() {
    var element = document.getElementById("style");
    element.classList.remove("divone");
    document.getElementById("style").textContent += ".divone{width: 400px; height: 35px; background-color: blue;}";
}
<!DOCTYPE html>
<html>
<head>
<style id="style">
.divone{
width: 500px;
height: 50px;
background-color: red;
}
</style>
</head>
<div class="divone">hello !!</div>
<div class="divtwo"></div>
<button onclick="myFunctionTest()">Click me</button>

As per your comment, here is how you can do it with an ID

function myFunctionTest() {
  var element = document.querySelectorAll("#style")[0].sheet;
  for (var i = 0; i < element.cssRules.length; i++) {
    if (element.cssRules[i].selectorText === '#divone') {
      element.deleteRule(i);
    }
  }
  document.getElementById("style").textContent += "#divone{width: 400px; height: 35px; background-color: blue;}";
}
<!DOCTYPE html>
<html>

<head>
  <style id="style">
    #divone {
      width: 500px;
      height: 50px;
      background-color: red;
    }
  </style>
</head>
<div id="divone">hello !!</div>
<div id="divtwo"></div>
<button onclick="myFunctionTest()">Click me</button>

Answer №2

  function customStyles() {
    document.getElementById("customStyle").remove();
    var css = '#divone{width: 400px; height: 35px; background-color: red;}',
    head = document.head || document.getElementsById('head')[0],
    style = document.createElement('style');

   head.appendChild(style);

   style.type = 'text/css';
   if (style.styleSheet){
  // Making sure it works on IE8 and below.
   style.styleSheet.cssText = css;
   } else {
      style.appendChild(document.createTextNode(css));
     }


  }

Answer №3

To change the CSS when a button is clicked, you can use the following code snippet.

  

  function myFunction() {
    document.getElementById('button').style.cssText = 'background-color: green; color: white; font-size: 44px';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<style id="style">
.divone{
width: 500px;
height: 50px;
background-color: red;
}
</style>
</head>
<div class="divone" id="button">hello !!</div>
<div class="divtwo"></div>
<button onclick="myFunction()">Click me</button>

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

Angular front-end rendering with Rails backend integration

Currently, I am working on a medium-sized Rails application and my latest endeavor is to integrate Angular into the system. After reviewing several tutorials, it appears that the most common method for fetching initial data and displaying the first view in ...

Is there a way to initiate an Angular event when clicking on an HTML input element within a Bootstrap 4 input-group?

Within my Bootstrap 4 input group, there is a prepended title along with two input fields. The structure looks like this: <div class="input-group" (click)="openDoc()"> <div class="input-group-prepend input-group-prepend-split rounded-0" ...

Halting the HTML-Embedded Video

Currently, I am utilizing a cross-browser embedding method like the following: <video width="549" height="309" controls poster="video/stills/index_demo_videoScreen.jpg" style="margin-top:20px;"> <source src="video/2014-reel-web.mp4" type="vid ...

Creating dependent dropdowns using Laravel Inertia Vue: A step-by-step guide

In my AddressController, I have a function called loadCity along with other CRUD functions: public function loadCities(Request $request) { $provinceId = $request->province_id; $cities = Province::where('province_id' ...

In Javascript, when trying to call Firebase database child(), it may sometimes result in the return value being "

Here is the current setup: Firebase Database: setores: { -KkBgUmX6BEeVyrudlfK: { id: '-KkBgUmX6BEeVyrudlfK', nome: 'test' } -KkDYxfwka8YM6uFOWpH: { id: '-KkDYxfwka8YM6uFOWpH', nome ...

Having trouble with Webpack dynamic import not returning files in ReactJS? Here's how to fix it

Struggling with importing and using images in Reactjs? I've imported all images from a folder but it's not returning an array with links. Take a look. function importAll(r) { return r.keys().map(r); } const images = importAll(requi ...

Guide on transferring files between Node.js/Express servers from receiving files at Server A to sending files to Server B

Currently, I'm tackling node.js express servers and I've hit a roadblock! Despite my efforts to scour the documentation and other resources, I can't seem to find the right solution. Here's what I need to accomplish: Receive 2-3 PDF ...

What is the best way to trigger the selection options in a dropdown menu with several buttons?

Is it possible to display the options from a select-option tag using a different button? I have either a div or another button. I want to be able to show the list of options from my select tag by clicking this button. Here is my select tag: <select&g ...

What is the most efficient method for importing mixins into vue.js?

Within my project, I have developed numerous mixins. Currently, my approach involves importing all of these mixins in the 'mixins/index.js' file and then importing them as needed in various components or pages. However, I am now questioning whet ...

A helpful tip for creating line breaks within a Vue JS v-for loop using CSS

I am looking to arrange the names in alphabetical order when a list item is clicked. My tools of choice are Vue.js and Flex Grid. The list item I am working with is called ListAll, When clicking on ListAll, I want to display all the records grouped by na ...

Every time I attempt to destructure the state object in react typescript, I encounter the error message stating 'Object is possibly undefined'

Whenever I attempt to destructure my state object in react typescript, I encounter an error stating Object is possibly 'undefined'. When I try using optional chaining, a different error pops up saying const newUser: NewUser | undefined Argument o ...

Struggling with TypeScript errors due to React.HTMLProps for HTMLAnchorElement

When trying to extend a React component with React.HTMLProps without explicitly defining onClick in the attribute list, ESLint complains when passing onClick as an attribute while using the component. Here's an example of the code: The React componen ...

How can dat.GUI convert values to degrees within the control panel in Three.js?

In the control panel, I created a basic slider to adjust the position and rotation of an object. Though adjusting the position is straightforward since the values are relative, I want to display the rotation values in degrees. This is the code snippet for ...

Merge data from api into visual charts using Google Chart Library

I received an API response with the following data structure: { "status": 200, "message": "OK", "data": [ { "_id": { "report_type": "robbery" }, "report_type": "robbery", "Counts": 11 }, { "_id": { "repo ...

Isolating a type as a constant in Typescript within a .js file?

Within my .js configuration files, I have a tsconfig containing the property checkJs: true. A library called Terser includes the following type options: ecma: 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 Despite setting ecma: 2017 in my configuration file ...

Performing a Jquery Ajax get request on multiple URLs within a single function

In my current setup, I have a form with a select dropdown and three submit buttons labeled as "Daily new likes", "Daily unlikes" and "Daily page views". The form includes an Ajax call within the submitForm function that sends the selected option value to a ...

Don't pay attention to CSS that is outside of the div

Currently, I am attempting to populate a div with templates in order to preview them. These templates are sourced from a database and configured using php. My issue lies in the fact that certain entries consist of entire websites (complete with a head and ...

The palindrome checking function is malfunctioning and needs to be fixed

I have attempted to create a function to determine if a number is a palindrome, but it seems to be malfunctioning. The concept is simple - splitting the number into two halves, comparing them, and reversing one half to check for symmetry. function palin ...

Incorporating dynamic HTML templates onto a webpage using JavaScript/jQuery for seamless

Looking for a solution to a coding issue I'm facing. Here's the situation: <template id="photo-template"> <div class="template-border"> <p class="name"></p> </div> </template> I need to displa ...

Version 5 of Material UI has a bug where the Grid component does not properly stretch

How can I make the Grid component stretch when one of the Card components contains extra text? You can view the sample code here. Changing the alignItems property to "flex-end" or "center" works, but when using alignItems: "stretch" it does not work. I ...