0

A function for creating style constructed as follows

function createStyle(css) {
  var head = document.head || document.getElementsByTagName("head")[0];
  var style = document.createElement("style");
  style.type = "text/css";
  if(style.styleSheet) {
    style.styleSheet.cssText = css;
  } else {
    var textNode = document.createTextNode(css);
    style.append(textNode);
  }
  head.append(style);
}

inspired by Christoph and TomFuertes code. Then it is called to create a style with class name tab

createStyle(`
  .tab button {
    background: inherit;
    float: left;
    outline: none;
    border: none;
    padding: 8px 6px;
    width: 60px;
    cursor: pointer;
  }
`);

and a HTML element using the style

var div = document.createElement("div");
div.className = "tab";
parent.append(div);

is also created. So it all works.

After that I need to modify the style with class name tab, where following code

var style = document.getElementsByTagName("style");
var css = style[0].innerHTML
var className = css.split(" ")[0].split(".")[1];

is used to get the style class name. I have managed to get the style class name tab and also the string containing the object in css.

The question is how I modify the style without I modify the string and recreate the style? Or if I have to do that, how I should delete the previous defined style if there are already some styles which I have not recorded the order for accessing them through array sytle[].

Proposed solution

Using How to change/remove CSS classes definitions at runtime? suggested by Achu I made this function

// Change style attribute with value
function changeStyleAttribute(style, attr, value) {
  var N = document.styleSheets.length;
  var styles = document.styleSheets;
  for(var i = 0; i < N; i++)
  {
    if(styles[i].rules[0].selectorText == style)
    styles[i].rules[0].style[attr] = value;
  }
}

which is called

changeStyleAttribute(".tab", "width", "299px");

and works. I hope there is another better and simpler solution.

dudung
  • 499
  • 2
  • 17

1 Answers1

0

You'll want to use document.styleSheets[i].cssRules which is an array you need to parse through to find the one you want, and then rule.style.setProperty('font-size','10px',null);

Refer to this link: How to change/remove CSS classes definitions at runtime?.

Hope this helps.

Achu
  • 272
  • 2
  • 10
  • Thank your for the link @Achu. And what should I do next? I edit my question and post the solution or I answer my question? The last seems rediculous, doesn't it? It is clear from https://stackoverflow.com/help/self-answer and not absurd :-). – dudung Jun 14 '18 at 00:49