add css style with javascript code example

Example 1: how to give css style in javascript

document.getElementById("myH1").style.color = "red";

Example 2: add css style sheet with javascript

<head>

<script>
function myFunction() {
  var x = document.createElement("LINK");
  x.setAttribute("rel", "stylesheet");
  x.setAttribute("type", "text/css");
  x.setAttribute("href", "styles.css");
  document.head.appendChild(x);
}
myFunction()
</script>

</head>

Example 3: change style js

// select element from DOM
const el = document.querySelector('.para')
// change css style
el.style.color = 'purple'

Example 4: js add css to document

document.querySelector('head').innerHTML += '<link rel="stylesheet" href="styles.css" type="text/css"/>';

Tags:

Css Example