style in js code example
Example 1: add style javascript
// Bad:
element.setAttribute("style", "background-color: red;");
// Good:
element.style.backgroundColor = "red";
Example 2: javascript style an element
// Getting the element first
var myElement = document.querySelector("#myElement");
// examples for updating styles
myElement.style.color = "blue";
myElement.style.backgroundColor = "red";
Example 3: js style
const title = document.querySelector('h1')
//title.setAttribute('style', 'margin: 50px');
console.log(title.style); // Show all style propertyes
console.log(title.style.color); // Log a color in console
title.style.margin = '50px'; // Set a margin of title
title.style.color='crimson'; // Set a color of title
title.style.fontSize = '60px'; // Set font size of title
Example 4: javascript style
// background-color
<element>.style.backgroundColor = '#000';
// background
<element>.style.background = '#000';
// color
<element>.style.color = '#fff';
// box-sizing
<element>.style.boxSizing = 'border-box';
// font-family
<element>.style.fontFamily = '\'Times New Roman\', Times, serif';
// font-size
<element>.style.fontSize = '16px';
// margin
<element>.style.margin = 0;
// padding
<element>.style.padding = '20px';
// width
<element>.style.width = '100%';
// height
<element>.style.height = '100%';
// margin-left
<element>.style.marginLeft = 0;
// font-weight
<element>.style.fontWeight = 400;
Example 5: document style
document.getElementById("myH1").style.color = "red";
Example 6: style through javascript
element.style.backgroundColor = "red"; // set the background color of an element to red