1

I have the following JavaScript code with inline CSS.

var container = display.getContainer();
container.style.cssText = 'width:100%;height:100%;z-index:100;object-fit: contain;';
document.body.appendChild(container);

I would like to move the inline CSS to the following class in style.css

.containerClass {
    width:100%;
    height:100%;
    z-index:100;
    object-fit: contain;
}

I have tried the following:

container.addClass('containerClass');

I've been unable to articulate my problem correctly, thus am having trouble finding the precise solution I am after.

Further -how would I go about telling the JavaScript file about the location of .containerClass?

2 Answers 2

1

Note: The classList property is not supported in Internet Explorer 9.

The following code will work in all browsers -

function addClass() {
  var element, name, arr;
  element = document.getElementById("container");
  name = "mystyle";
  arr = element.className.split(" ");
  if (arr.indexOf(name) == -1) {
    element.className += " " + name;
  }
}
.mystyle {
  background-color: black;
  color: white;
}

div {
  margin-top: 20px;
  width: 100%;
  padding: 25px;
  font-size: 25px;
  box-sizing: border-box;
  border: 1px solid #000;
}
<p>Click the "Add Class" button to add the "mystyle" class to the container element:</p>

<button onclick="addClass()">Add Class</button>

<div id="container">This is a DIV element.</div>

Sign up to request clarification or add additional context in comments.

Comments

1

In you style.css, define the properties for .containerClass.

style.css :

.containerClass {
    width:100%;
    height:100%;
    z-index:100;
    object-fit: contain;
}

When you want to add this styling, just add that class to the element you want to using javascript. Javascript:

var container = document.getElementById("elementId");
container.classList.add("containerClass");

3 Comments

Beautiful. Now how to I tell the JS file how to find that class in the CSS file?
You don't need to tell anything to javascript. Say for example you want to add .containerClass to a <div id="someId">...</div>. After running the above code, the div will become <div id="someId" class="containerClass">...</div> and the style will be automatically applied.
Just don't forget to include you style.css in your html file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.