Color de fondo CSS en JavaScript


¿Cómo puedo configurar el color de fondo CSS de un elemento HTML usando JavaScript?

Author: shishir, 2008-08-06

16 answers

En general, las propiedades CSS se convierten a JavaScript convirtiéndolas en camelCase sin guiones. Así que background-color se convierte en backgroundColor.

function setColor(element, color)
{
    element.style.backgroundColor = color;
}
 139
Author: David Wengier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-01 01:43:49

Puede encontrar que su código es más fácil de mantener si mantiene todos sus estilos, etc. en CSS y simplemente establecer / desajustar nombres de clase en JavaScript.

Su CSS obviamente sería algo como:

.highlight {
    background:#ff00aa;
}

Luego en JavaScript:

element.className = element.className === 'highlight' ? '' : 'highlight';
 28
Author: Ian Oxley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-14 18:58:04
var element = document.getElementById('element');
element.style.background = '#FF00AA';
 22
Author: tags2k,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-07 18:55:16

O, usando un poco de jQuery:

$('#fieldID').css('background-color', '#FF6600');
 20
Author: Wally Lawless,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-08-06 13:23:42

Agregue este elemento script a su elemento body:

<body>
  <script type="text/javascript">
     document.body.style.backgroundColor = "#AAAAAA";
  </script>
</body>
 7
Author: james.garriss,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-03 21:20:56

var element = document.getElementById('element');

element.onclick = function() {
  element.classList.add('backGroundColor');
  
  setTimeout(function() {
    element.classList.remove('backGroundColor');
  }, 2000);
};
.backGroundColor {
    background-color: green;
}
<div id="element">Click Me</div>
 6
Author: Roger Causto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-10 15:56:12

Puedes probar esto

var element = document.getElementById('element_id');
element.style.backgroundColor = "color or color_code";

Ejemplo.

var element = document.getElementById('firstname');
element.style.backgroundColor = "green";//Or #ff55ff

JSFIDDLE

 4
Author: Ajay Gupta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-04 12:09:19

Puedes hacerlo con jQuery:

$(".class").css("background","yellow");
 4
Author: bluelog,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-28 12:51:29

KISS Respuesta:

document.getElementById('element').style.background = '#DD00DD';
 3
Author: Zardiw,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-10 16:08:13

Puedes usar:

  <script type="text/javascript">
     Window.body.style.backgroundColor = "#5a5a5a";
  </script>
 3
Author: Saeed Py,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-05 12:51:06
$('#ID / .Class').css('background-color', '#FF6600');

Usando jquery podemos apuntar a la clase o Id del elemento para aplicar css background o cualquier otro estilo

 3
Author: pragadeesh mahendran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-23 09:56:47
$("body").css("background","green"); //jQuery

document.body.style.backgroundColor = "green"; //javascript

Hay tantas maneras que creo que es muy fácil y simple

Demo En Plunker

 2
Author: Srikrushna Pal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-13 20:57:53

Puede usar

$('#elementID').css('background-color', '#C0C0C0');
 1
Author: hamed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-11 01:56:56

Cambiar el CSS de un HTMLElement

Puede cambiar la mayoría de las propiedades CSS con JavaScript, use esta instrucción:

document.querySelector(<selector>).style[<property>] = <new style>

Donde <selector>, <property>, <new style> son todos los objetos String.

Normalmente, la propiedad style tendrá el mismo nombre que el nombre real usado en CSS. Pero siempre que haya más de una palabra, será camel case: por ejemplo background-color se cambia por backgroundColor.

La siguiente instrucción establecerá el fondo de #container al color rojo:

documentquerySelector('#container').style.background = 'red'

Aquí hay una demostración rápida cambiando el color de la caja cada 0.5 s:

colors = ['rosybrown', 'cornflowerblue', 'pink', 'lightblue', 'lemonchiffon', 'lightgrey', 'lightcoral', 'blueviolet', 'firebrick', 'fuchsia', 'lightgreen', 'red', 'purple', 'cyan']

let i = 0
setInterval(() => {
  const random = Math.floor(Math.random()*colors.length)
  document.querySelector('.box').style.background = colors[random];
}, 500)
.box {
  width: 100px;
  height: 100px;
}
<div class="box"></div>

Cambiar CSS de múltiples HTMLElement

Imagine que le gustaría aplicar estilos CSS a más de un elemento, por ejemplo, hacer que el color de fondo de todos los elementos con el nombre de la clasebox lightgreen. Entonces usted puede:

  1. Seleccione los elementos con .querySelectorAll y desenvuelva en un objeto Array con el sintaxis de desestructuración :

    const elements = [...document.querySelectorAll('.box')]
    
  2. Bucle sobre la matriz con .forEach y aplicar el cambio a cada elemento:

    elements.forEach(element => element.style.background = 'lightgreen')
    

Aquí está la demo:

const elements = [...document.querySelectorAll('.box')]
elements.forEach(element => element.style.background = 'lightgreen')
.box {
  height: 100px;
  width: 100px;
  display: inline-block;
  margin: 10px;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

Otro método

Si desea cambiar varias propiedades de estilo de un elemento más de una vez, puede considerar usar otro método: vincule este elemento a otra clase en su lugar.

Suponiendo que se puede preparar el estilos de antemano en CSS puede alternar clases accediendo al classList del elemento y llamando a la función toggle:

document.querySelector('.box').classList.toggle('orange')
.box {
  width: 100px;
  height: 100px;
}

.orange {
  background: orange;
}
<div class='box'></div>

Lista de propiedades CSS en JavaScript

Aquí está la lista completa:

alignContent
alignItems
alignSelf
animation
animationDelay
animationDirection
animationDuration
animationFillMode
animationIterationCount
animationName
animationTimingFunction
animationPlayState
background
backgroundAttachment
backgroundColor
backgroundImage
backgroundPosition
backgroundRepeat
backgroundClip
backgroundOrigin
backgroundSize</a></td>
backfaceVisibility
borderBottom
borderBottomColor
borderBottomLeftRadius
borderBottomRightRadius
borderBottomStyle
borderBottomWidth
borderCollapse
borderColor
borderImage
borderImageOutset
borderImageRepeat
borderImageSlice
borderImageSource  
borderImageWidth
borderLeft
borderLeftColor
borderLeftStyle
borderLeftWidth
borderRadius
borderRight
borderRightColor
borderRightStyle
borderRightWidth
borderSpacing
borderStyle
borderTop
borderTopColor
borderTopLeftRadius
borderTopRightRadius
borderTopStyle
borderTopWidth
borderWidth
bottom
boxShadow
boxSizing
captionSide
clear
clip
color
columnCount
columnFill
columnGap
columnRule
columnRuleColor
columnRuleStyle
columnRuleWidth
columns
columnSpan
columnWidth
counterIncrement
counterReset
cursor
direction
display
emptyCells
filter
flex
flexBasis
flexDirection
flexFlow
flexGrow
flexShrink
flexWrap
content
fontStretch
hangingPunctuation
height
hyphens
icon
imageOrientation
navDown
navIndex
navLeft
navRight
navUp>
cssFloat
font
fontFamily
fontSize
fontStyle
fontVariant
fontWeight
fontSizeAdjust
justifyContent
left
letterSpacing
lineHeight
listStyle
listStyleImage
listStylePosition
listStyleType
margin
marginBottom
marginLeft
marginRight
marginTop
maxHeight
maxWidth
minHeight
minWidth
opacity
order
orphans
outline
outlineColor
outlineOffset
outlineStyle
outlineWidth
overflow
overflowX
overflowY
padding
paddingBottom
paddingLeft
paddingRight
paddingTop
pageBreakAfter
pageBreakBefore
pageBreakInside
perspective
perspectiveOrigin
position
quotes
resize
right
tableLayout
tabSize
textAlign
textAlignLast
textDecoration
textDecorationColor
textDecorationLine
textDecorationStyle
textIndent
textOverflow
textShadow
textTransform
textJustify
top
transform
transformOrigin
transformStyle
transition
transitionProperty
transitionDuration
transitionTimingFunction
transitionDelay
unicodeBidi
userSelect
verticalAlign
visibility
voiceBalance
voiceDuration
voicePitch
voicePitchRange
voiceRate
voiceStress
voiceVolume
whiteSpace
width
wordBreak
wordSpacing
wordWrap
widows
writingMode
zIndex
 0
Author: Ivan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-08 11:41:00
$(".class")[0].style.background = "blue";
 -1
Author: Jeff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-11 11:34:15

Javascript:

document.getElementById("ID").style.background = "colorName"; //JS ID

document.getElementsByClassName("ClassName")[0].style.background = "colorName"; //JS Class
[2]} Jquery:
$('#ID/.className').css("background","colorName") // One style

$('#ID/.className').css({"background":"colorName","color":"colorname"}); //Multiple style
 -1
Author: Mr.Pandya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-23 10:02:59