Using JavaScript to change an element's background color via CSS

Hey everyone! I’m trying to figure out how to change the background color of an HTML element using JavaScript. I know we can do this with CSS, but I need to make it happen dynamically with JS. Does anyone know the best way to go about this?

Here’s what I’ve tried so far:

function changeColor(elementId, newColor) {
  let targetElement = document.getElementById(elementId);
  targetElement.style.backgroundColor = newColor;
}

// Usage
changeColor('myDiv', 'blue');

This kind of works, but I’m wondering if there’s a better or more efficient way to do it. Maybe using classList or something? Any tips or tricks would be super helpful. Thanks in advance!

Your current approach is valid, but there’s another method worth considering. I’ve had success using the setAttribute() function, which can be more performant in certain scenarios. Here’s an example:

function changeBackgroundColor(elementId, color) {
document.getElementById(elementId).setAttribute(‘style’, background-color: ${color};);
}

This method directly sets the style attribute, which can be beneficial when dealing with multiple style changes simultaneously. It’s also quite straightforward and easy to read.

One caveat: this approach will overwrite any existing inline styles. If that’s a concern, you might want to stick with your original method or combine approaches based on your specific use case.

hey neo_stars, ur approach looks solid! another option is using classList.add() to apply a predefined CSS class. like this:

document.getElementById(‘myDiv’).classList.add(‘blue-bg’);

where .blue-bg {background-color: blue;} is in ur CSS. this can b cleaner if u have multiple style changes.

Your current method works fine, but there’s another approach worth considering. I’ve found that using CSS custom properties (variables) can be quite flexible. Here’s how I’ve implemented it:

function setColor(elementId, color) {
  document.documentElement.style.setProperty('--dynamic-bg', color);
  document.getElementById(elementId).style.backgroundColor = 'var(--dynamic-bg)';
}

This way, you can easily update multiple elements sharing the same variable. It’s also great for theming. Just make sure to define the custom property in your CSS:

:root {
  --dynamic-bg: initial;
}

I’ve used this method in several projects, and it’s proven to be quite scalable and maintainable.