Friday, October 20, 2017

CSS background color of an HTML element using JavaScript

CSS background color in JavaScript. How can I set the CSS background color of an HTML element using JavaScript? This is a common question. You can do this using various tricks. Today we learn how to set CSS background color in JavaScript.

Process One:- You might find your code is more maintainable if you keep all your styles, etc. in CSS and just set or unset CSS class names in JavaScript. Your CSS would obviously be something like:
Then in JavaScript:
element.className = element.className === 'bgcolor' ? '' : 'bgcolor';
This is valid in most cases, but not in cases where the color (or whatever attribute) is defined in configuration, or user entered, you can't create a CSS class for every possible color
Process Two:-
var element = document.getElementById('element'); = '#ddd';
Process Three:- Using a little jQuery:
 $('#yourid').css('background-color', '#ddd');
Process Four:- = "green"; //javascript
$("body").css("background","green"); //jQuery

How to practice tutorials…

  • Make a team with your friends (Member should be 4/5).
  • Start to practice one tutorial series along with them.
  • Don’t try to collect source code. Type the code while watching the tutorial.
  • If you face any problem, discuss with team members to solve quickly.