Burak Tokak
Burak Tokak

Reputation: 1850

Changing <style>'s innerHTML for adding new style lines?

I have a solution for my problem, but im looking for a more efficient way to solve it.

I basicly want to code a function, that adds new lines of styles in css with Javascript.

My solution is this.

function addStyle(newStyleLine){
var mainStyle = document.getElementsByTagName("style")[0];
mainStyle.innerHTML = mainStyle.innerHTML + "body {"+newStyleLine+"}";
}

And i have a <style> tag in my html. It works fine, but i think when i will have a bigger css in the <style> it will not be that efficient.

Does anybody have thoughts about a better way to solve this.

Thank you.

Upvotes: 1

Views: 94

Answers (1)

epascarello
epascarello

Reputation: 207501

Use the methods built in that allow you to add new rules to the stylesheet.

Syntax

stylesheet.insertRule(rule, index)

Parameters

  • rule is a DOMString containing the rule to be inserted (selector and declaration).
  • index is a unsigned int representing the position to be inserted.

https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet.insertRule

Upvotes: 2

Related Questions