Last updated: Mar 5, 2024
Reading time·3 min

To create a style tag:
document.createElement() method to create the style tag.textContent property to assign styles to the tag.style tag to the head using the appendChild() method.Here is the HTML for the examples.
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <meta charset="UTF-8" /> </head> <body> <div id="box">Apple, Pear, Banana</div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const style = document.createElement('style'); style.textContent = ` #box { width: 100px; height: 100px; background-color: salmon; color: white; } body { background-color: lightgrey; } `; document.head.appendChild(style);

We used the
document.createElement() to create
a style element.
The createElement method returns the newly created element.
We used the textContent property to assign some styles to the element.
Notice that we used backticks `` (not single quotes) to be able to use a multi-line string when setting the element's text content.
textContent property represents the text content of the element and its descendants. This is exactly what we need when adding styles to a style tag.The
document.head
property returns the head element of the current document.
We called the
appendChild()
method to append the style tag to the head element on the page.
If I open the page from the example, I can see that the style tag has been
created successfully.

You can also use the Element.insertAdjacentHTML() method to create a style tag.
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <meta charset="UTF-8" /> </head> <body> <div id="box">Apple, Pear, Banana</div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const style = ` <style> #box { width: 100px; height: 100px; background-color: orange; color: white; } body { background-color: lightgrey; } </style> `; document.head.insertAdjacentHTML('beforeend', style);

Make sure to wrap the contents of the style variable in backticks ``, not in
single quotes.
We placed the style tag right before the closing head tag.
The insertAdjacentHTML() method takes the following 2 parameters:
position - the position relative to the element where the HTML should be
inserted. Can be one of the following:
beforebegin - before the element itself.afterbegin - just inside the element, before its first child.beforeend - just inside the element, after its last child.afterend - after the element itself.text - the string to be parsed as HTML and inserted into the DOM.
It should be noted that you shouldn't append HTML that is from user-generated input without escaping it.
You can learn more about the related topics by checking out the following tutorials: