Attempting to change background color using JavaScript

As a newcomer to JavaScript, I am eager to learn how to use it to change the background color of an element by altering its class. Despite combining code snippets from various sources, my attempt is not yielding the desired results and the reason eludes me.

 
function myFunc() {
   var y = document.getElementById("bg-change1").getAttribute("class");
   if (y === "normal") {
     y = "active";
   } else {
     y = "normal";
   }
 }
.normal {
  background-color: white;
}

.active {
  background-color: green;
}
<body>
  <button onclick="myFunc()">click here</button>
  <div id="bg-change1" class="normal">
    <p>Lorem ipsum and etc</p>
  </div>
</body>

Answer №1

In order to complete the task successfully, it is imperative that you assign the value at the end rather than just retrieving it. The missing piece in your function is the line

document.getElementById("bg-change1").setAttribute("class",y);
which needs to be added at the end.

function myFunc() {
   var y = document.getElementById("bg-change1").getAttribute("class");
   if (y === "normal") {
     y = "active";
   } else {
     y = "normal";
   }
   document.getElementById("bg-change1").setAttribute("class",y);
 }
.normal {
  background-color: white;
}

.active {
  background-color: green;
}
<body>
  <button onclick="myFunc()">click here</button>
  <div id="bg-change1" class="normal">
    <p>Lorem ipsum and etc</p>
  </div>
</body>

Answer №2

If you're looking to achieve this with vanilla JavaScript in a concise way, here's how you can do it:

function toggleClass() {
   var element = document.getElementById("bg-change1");
   element.classList.toggle("active");
}

Just ensure that the CSS selector order prioritizes the '.active' class over '.normal' for this effect to work as intended.

Answer №3

There's a more efficient way to toggle a class using the method below:

 
 function myFunc() {
   var y = document.getElementById("bg-change1");
   y.classList.toggle("active");
 }
.normal {
  background-color: white;
}

.active {
  background-color: green;
}
<body>
  <button onclick="myFunc()">click here</button>
  <div id="bg-change1" class="normal">
    <p>Lorem ipsum and etc</p>
  </div>
</body>

Answer №4

When you call getAttribute("class"), it retrieves the attribute's content at that specific moment. Since this content is a string, there is no connection to the element itself. Thus, reassigning <code>y
has no effect.

If you want to actually modify the attribute, you can use setAttribute("class", "active"). However, this solution may not be ideal as it restricts you to only one class and renders the "normal" class redundant.

Instead, apply default styles using a different selector (e.g., #bg-change1) and override properties as needed in the .active selector. This allows you to toggle between both states using document.getElementById("bg-change1").classList.toggle("active").

Answer №5

One way to manipulate a class name in JavaScript is by retrieving the current class of an element and then changing it based on certain conditions. However, this approach does not automatically update the class attribute of the element.

An alternative method to achieve the same result is by using a function like the following:

function myFunc() {
  var y = document.getElementById("bg-change1").getAttribute("class");
  if (y === "normal") {
    document.getElementById("bg-change1").classList.remove('normal');
    document.getElementById("bg-change1").classList.add('active');
  } else {
    document.getElementById("bg-change1").classList.remove('active');
    document.getElementById("bg-change1").classList.add('normal');
  }
}

Answer №6

You have successfully retrieved the attribute, but now it's time to make changes and set it. Use the following code:

document.getElementById("bg-change1").setAttribute("class", y);

For example:

function updateClass() {
  var y = document.getElementById("bg-change1").getAttribute("class");
  if (y === "normal") {
    y = "active";
  } else {
    y = "normal";
  }
  document.getElementById("bg-change1").setAttribute("class", y);
}
.normal {
  background-color: white;
}

.active {
  background-color: green;
}
<button onclick="updateClass()">Click here</button>
<div id="bg-change1" class="normal">
  <p>Lorem ipsum and more</p>
</div>

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

Having trouble constructing the Grand-Stack-Starter api because babel-node is not being recognized

As I endeavor to create the initial api for the Grand Stack Starter, I encounter difficulties every time I try to execute npm start: >nodemon --exec babel-node src/index.js [nodemon] 1.18.7 [nodemon] to restart at any time, enter `rs` [nodemon] watchi ...

Dealing with AJAX errors consistently in jQuery

Is it possible to efficiently handle 401 errors in AJAX calls and redirect to login.html without repeating the same code over and over again? if (xhr.status === 401) { location.assign('/login.html'); } I am seeking a way to manage these erro ...

AngularJS ng-repeat specific filter conditions

Below is the code that I currently have: <div data-ng-if="hasSelectedCompany"> <tbody data-ng-repeat="driver in result.applications | filter: { name: selectedApplication } track by $index"> </div> <div data-ng-if="hasSelectedSuppor ...

Vue caution: The reference to property or method "list" during render is not defined on the instance. Ensure that this property is reactive and properly declared

I'm currently exploring the characters from the Rick & Morty series app using vue.js, and I am still learning how to use vue.js. However, I encountered the following error and would appreciate help in resolving it: Error1: [Vue warn]: Property or me ...

Combining an array of intricate data models to create

Currently, my setup involves using Entity Framework 7 in conjunction with ASP.NET MVC 5. In my application, I have various forms that resemble the design showcased in this image. By clicking on the "new" button within these forms, a Bootstrap modal like t ...

Adjust the position of an object in Three.js based on the scale of another object

Sharing a helpful solution for a recent problem I faced in case it can assist someone else. Imagine you have a House object with a Chair inside it positioned in a particular spot. If you scale the House's size by 2, the Chair will no longer be in the ...

What is the trick to creating uneven sides (lower left and lower right) with varying heights?

Struggling to articulate my design vision, I'm attempting to achieve a unique look. Although I've explored the transform function, it's not quite what I'm looking for. Instead of rotating the div, I want a diagonal ending. Can this des ...

Leveraging jQuery to target elements with a minimum of two child elements

How can I use jQuery to specifically target .sortable <ul> elements that have 2 or more children (<li> elements)? Is there a way for jQuery to select only <ul> elements with at least 2 <li> children? Thanks in advance! The current ...

What are the time-saving benefits of utilizing semantic X/HTML in CSS development?

Exploring the Time-Saving Power of Semantic X/HTML Markup - Streamlining CSS writing for websites Adapting to future design changes from clients with ease Avoiding the time-consuming nature of Table-based layouts in all scenarios Today, I have the task ...

Apache causes HTML download tag to malfunction

I have an HTML file that includes the following code: <a href="/Library/WebServer/Documents/file.zip" download="file.zip"> Download here </a> When I test this HTML page on Chrome, it successfully allows me to download the file. However, when ...

Sprite hover image in IE9 not aligned properly or blurry by 1 pixel

I have implemented a sprite to display my button image and a slightly darker hover image. Below is the CSS code I am using, with my image being 31px tall: a { background-position: 0 0; } a:hover { background-position: 0 -31px; } Although the ho ...

Incorporating external JavaScript into a Rails application

Having trouble with the syntax on this simple problem. Struggling to find examples of externally linked files, all solutions online involve storing a local copy instead. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" typ ...

Anomalous sorting methods found in JavaScript arrays

While attempting to sort a JavaScript array, I came across an unexpected behavior. var arr = ['a', 'b', 'C', 'd', 'e', 'f', 'g', 'h', 'I', 'k']; arr.sor ...

JavaScript will continue to process the submit to the server even after validation has been completed

My current challenge involves implementing form validation using JavaScript. The goal is to prevent the form from being sent to the server if any errors are found. I have made sure that my JavaScript function returns false in case of an error, like so: ...

Tips for making an input field that overlays text

I am currently working on a project that involves creating multiple cards using Bootstrap. Each card consists of a header, body, and footer. When a card is clicked on, I want an input field to appear in the header, footer, and body sections, overlaying the ...

What steps can I take to ensure that my $genderRadio variable is properly defined?

Currently, I am conducting a survey where I ask participants if they work out frequently or not. Depending on their answer, I have different sets of questions for both scenarios. Additionally, I inquire about the gender of the respondents. My ultimate aim ...

Encountered a problem while trying to fetch over 1000 records from the server using $

When fetching records from a database using JSON in $.ajax and ASP.net, everything runs smoothly. However, if the number of records exceeds 1000, it crashes and displays a "500 (Internal Server Error)" message. Below is the jQuery code: $.ajax({ ...

Tips for adjusting the height of MUI Date Picker to fit your preferences

<Box sx={{ m: 1 }}> <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePicker label="Enter Date" slotProps={{ textField: { height: "10px" } }} ...

"Sorry, cannot make a request for the relation field at

I am encountering difficulties when attempting to retrieve the relation field from the API. export async function fetchContent(params) { const reqOptions = { headers: { Authorization: `Bearer ${process.env.API_TOKEN}` } ...

What methods can I use in JavaScript to modify input values and update them in my HTML output?

How can I retrieve the input number value in HTML, perform a mathematical formula with the value when it changes, and display the updated data on the page without reloading? This is my HTML: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3. ...