9/24/2018 - 6:41 AM



function changeCSSStyle(id) {
  var p = document.querySelector("#p1"); = 'red';
  p.innerHTML = 'style.color used to change the color';

  p = document.querySelector("#p2"); = 'lightGreen';
  p.innerHTML = 'style.backgroundColor used';

  p = document.querySelector("#p3"); = '100px';
  p.innerHTML = 'style.leftMargin used to shift this paragraph 100px to the right';
  p = document.querySelector("#p4"); = '2px solid blue'; = "20px";
  p.innerHTML = 'style.border and style.padding (internal margins) used';

  p = document.querySelector("#p6"); = 'center'; = "1px dashed red";
  // for boxShadow: h-shadow v-shadow blur spread color = "2px 2px 5px 0px grey";
  p.innerHTML = 'style.textAlign, style.border, style.bowShadow used';



A Pen by Pan Doul on CodePen.


<!DOCTYPE html>
<html lang="en">


Changing the style of selected HTML elements
The style attribute: how to modify an HTML element's CSS properties from JavaScript
The most common way to modify the CSS style of one of several elements you selected using the DOM or Selector API, is to use the style attribute.

Typical use:

// select the paragraph with id = "paragraph1"
var p = document.querySelector('#paragraph1');
// change its color = 'red';
Warning: with the style attribute, you can modify (or read) any CSS property, but be careful: the syntax changes a little due to the fact that in JavaScript the "-" is a math operator, while in CSS it is used to separate properties made of multiple words, such as background-color.

When using such properties from JavaScript, the rule is simple:

Remove the "-" sign,
Capitalize the word after the "-" sign!
Simple, isn't it?


text-align becomes style.textAlign
margin-left becomes style.marginLeft
The most useful CSS properties (we do recommend that you follow the W3Cx courses CSS basics, CSS and HTML5 fundamentals from W3Cx to learn more about CSS):

color: changing the color of the text content of selected element(s),
background-color: same but this time the background color,
margin and padding properties (external and internal margins), including their variants: margin-left, margin-top, margin-right, margin-bottom, also padding-left, etc.
border and border-radius: change the border, type (plain, dashed), color, thickness, rounded corners etc.
box-shadow to add shadows to selected elements, 
font, font-style: font characters and style (italic, bold, plain)
text-align (centered, etc.)

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Change background color of p under an element whose id is known</title>
  <button onclick="changeCSSStyle();">Change different properties of the paragraphs, using the style attribute</button>
<div id="firstDiv">
  <p id="p1">Paragraph 1.</p>
  <p id="p2">Paragraph 2.</p> 
  <p id="p3">Paragraph 3.</p>
  <p id="p4">Paragraph 4.</p>
  <p id="p5">Paragraph 5.</p>
  <p id="p6">Paragraph 6.</p>