Categories
JavaScript Answers

How to Create a style Tag with JavaScript?

Spread the love

Sometimes, we may want to create a style tag dynamically within our web page.

In this article, we’ll look at how to create a style tag dynamically with JavaScript.

Create a style Element with createElement Attach it to the head Tag with appendChild

We can create a style element with the docuemnt.createElement method as we do with any other kind of element.

Then we can attach the created element to the head tag by writing:

const style = document.createElement('style')
style.type = 'text/css';
style.textContent = 'h1 { color: green }';
document.head.appendChild(style)

We create the style element with document.createElement .

Then we set the type property of it to 'text/css' .

And then we set the textContent of the style element to the styles we want.

Finally, we call document.head.appendChild to append the style element to the head tag as a child.

We can now add the following HTML:

<h1>
  hello
</h1>

And we that the h1 text is green.

document.head.insertAdjacentHTML Method

We can also use the document.head.insertAdjacentHTML method to add our own HTML into the head tag.

This includes inserting a style element into the head tag.

To do this, we write:

document.head.insertAdjacentHTML("beforeend", `
  <style>
    h1 { color :green }
  </style>
`)

We pass in beforeend to insert the style element before the closinghead tag.

And so we get the same result as before.

Inserting a Stylesheet Dynamically

We can also insert a CSS stylesheet dynamically.

For instance, we can write:

const ss = document.createElement("link");
ss.type = "text/css";
ss.rel = "stylesheet";
ss.href = "https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css";
document.head.appendChild(ss);

We create the link element with the document.createElement method.

Then we set the type to 'text/css' to make it reference a CSS stylesheet.

rel sets the rel attribute to stylesheet .

href sets the href attribute to the CSS file we want to reference.

Then we call document.head.appendChild to append the CSS.

And now we get the styles from the Bootstrap stylesheet applied in our app.

Conclusion

We can create a style element with JavaScript or add a link tag dynamically to reference to external CSS with JavaScript to add styles dynamically.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *