how to link a style css in javascript code example

Example 1: 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 2: js add css to document

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

Tags:

Css Example