How can I set the CSS background color of an HTML element using JavaScript?
original title: "How to set CSS background color of HTML using JavaScript"
How can I set the CSS background color of an HTML element using JavaScript?
Как установить цвет фона CSS для элемента HTML с помощью JavaScript?
Это резюме после перевода, если вам нужно просмотреть полный перевод, нажмите значок «перевести»
In general, CSS properties are converted to JavaScript by making them camelCase without any dashes. So
background-color
becomesbackgroundColor
.You might find your code is more maintainable if you keep all your styles, etc. in CSS and just set / unset class names in JavaScript.
Your CSS would obviously be something like:
Then in JavaScript:
Or, using a little jQuery:
Add this script element to your body element:
You can try this
Example.
JSFIDDLE
You can do it with JQuery:
KISS Answer:
You can use:
so many ways are there I think it is very easy and simple
Demo On Plunker
By using jquery we can target the element's class or Id to apply css background or any other stylings
you can use
Javascript:
Jquery:
Changing CSS of a
HTMLElement
You can change most of the CSS properties with JavaScript, use this statement:
where
<selector>
,<property>
,<new style>
are allString
objects.Usually, the style property will have the same name as the actual name used in CSS. But whenever there is more that one word, it will be camel case: for example
background-color
is changed withbackgroundColor
.The following statement will set the background of
#container
to the color red:Here's a quick demo changing the color of the box every 0.5s:
Похожие проблемы
Недавние проблемы
Licensed under cc by-sa 3.0 with attribution required.