Javascript DOM CSS Style object create for head section

Introduction

We can create a <style> element via the document.createElement() method:

var x = document.createElement("STYLE");

Click the button to create a STYLE element, and place it in the head section.

The created style element contains css declarations that will change the font properties of this document.

View in separate window

<!DOCTYPE html>
<html>
<head>
</head>//  w ww.  jav a  2s. c  om
<body>
<p>test test</p>
<button onclick="myFunction()">Test</button>
<script>
function myFunction() {
  var x = document.createElement("STYLE");
  var t = document.createTextNode("body {font: 20px verdana;}");
  x.appendChild(t);
  document.head.appendChild(x);
}
</script>

</body>
</html>



PreviousNext

Related