Material Box

Material Box

WEB Design & Material Images

JavaScript - Add CSS style tag inside head tag


A simple code example to add a CSS <style> tag inside the <head> tag using JavaScript.

The HTML has a <head> tag where CSS will be appended to change the style of the target element.

<div id="target">Element whose style will be changed<br>by appending CSS to the head tag</div>

JavaScript creates a <style> tag with createElement(), and specifies the CSS code to insert with the textContent property.

Selects the <head> tag with document.querySelector('head'), and appends the created <style> tag inside it at the end with appendChild().

The code below appends a <style> tag from the script, and changes the style of the target HTML element.

// Create style element
let style = document.createElement('style');

// Set contents of style element
style.textContent =  '#target { padding: 10px; background-color: blueviolet; border-radius: 10px;}';

// Append style element at end of head

JavaScript - Add CSS style tag inside head tag

TitleJavaScript - Add CSS style tag inside head tag