0

What is the best way to apply a css rule in javascript only for a specific element ?

JSBIN example

After appending the constructed container to the DOM i want to set the rule for the new element to

'table-container > span { width : ' + calculated_width + 'px } ';

The size may change so i'm trying to avoid setting it directly on the child elements. there might be several elements like this on the page so i can't set it globally in the main stylesheet.

Thanks.

haki
  • 9,389
  • 15
  • 62
  • 110

1 Answers1

0

Give the specific container an additional, generated class name and add a style element (here's how) with the relevant rule, e.g.:

.array-container.width-28 > span { width : 28px }

...if the width you want is 28px.

You'd change this line:

container.setAttribute('class','array-container');

to

container.className = 'array-container width-' + width;

Keep track of the style elements you add so that if you need a value twice, you don't have to add a second style element for the same value.

Here's a really quick and dirty example: Live Copy

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Dynamic Style Example</title>
  <style>
    .array-container span {
      display: inline-block;
      border: 1px solid #08f;
      height: 1em;
    }
  </style>
</head>
<body>
  <label>Add elements with width:
    <input type="number" value="10" min="10" max="10000" id="width-to-use">
  </label>
  <input type="button" value="Add" id="btn-add">
  <script>
    (function() {
      document.getElementById("btn-add").onclick = function() {
        var width, div, css, style;

        width = parseInt(document.getElementById("width-to-use").value, 10);
        if (isNaN(width)) {
          return;
        }

        div = document.createElement('div');
        div.innerHTML =
          "<span></span>" +
          "<span></span>" +
          "<span></span>";
        div.className = "array-container width-" + width;

        if (document.getElementById("style-width-" + width) === null) {
          css = ".array-container.width-" + width + " span { " +
            "width: " + width + "px; " +
            "}";
          style = document.createElement('style');
          style.id = "style-width-" + width;
          style.type = "text/css";
          if (style.styleSheet){
            style.styleSheet.cssText = css;
          }
          else {
            style.appendChild(document.createTextNode(css));
          }
          document.getElementsByTagName("head")[0].appendChild(style);
        }

        document.body.appendChild(div);
      };
      function display(msg) {
        var p = document.createElement('p');
        p.innerHTML = String(msg);
        document.body.appendChild(p);
      }
    })();
  </script>
</body>
</html>
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875