Home > Enterprise >  How to change a css value in javascript?
How to change a css value in javascript?

Time:09-06

So I want to change a css value in javascript, without having an element in html, I'll explain like:

<style>
.box{
width: 10%;
}
</style>
<script>
// I want to change the width value of (.box) to something like "90%" 
</script>

So what I mean to say is that I want to change the (.box) width value between the two style tags, I know my question sounds weird, but am just new coding and I really need it, any help appreciated!

CodePudding user response:

Use media queries.

I don't remember the exact way to do this, but something like:

.box { width: 90%; }

@media screen and (min-width: 1000px) {
    .box { width: 40%; }
}

CodePudding user response:

You can change the properties (e.g. width) of a CSSStyleDeclaration with its setProperty() method.

You can get a CSSStyleSheet of a specific <style> element with its sheet property.

In our case, the stylesheet's first CSSStyleRule (sheet.cssRules[0]) is for the CSS class .box. You get the CSSStyleDeclaration object of a CSSStyleRule with its style property.

Example:

const iClass = document.getElementById("i-class");
const classRule = document.getElementById("my-style").sheet.cssRules[0];

// Set input.value to initial width-value (10%)
iClass.value = classRule.style.getPropertyValue("width");

// Update width-value on each input
iClass.addEventListener("input", () => {
  classRule.style.setProperty("width", iClass.value);
});
/* Ignore; presentational styling */
.box {
  margin-bottom: .5rem;
  aspect-ratio: 1/1;
  background-color: coral;
  text-align: center;
}
<style id="my-style">
.box{
  width: 10%;
}
</style>

<div>
  <label for="i-class">Class width:</label> <input id="i-class">
</div>

<div >class</div>

Unlike adding a new CSS rule, this changes the existing rule.

CodePudding user response:

Here's one option, adding a <style> tag dynamically

var inline_style = `
  .box {
    width: 90%; 
    background: pink; 
  }`;

// from https://stackoverflow.com/a/28662118/3807365
document.head.insertAdjacentHTML("beforeend", '<style>'   inline_style   '</style>')
.box {
  width: 10%;
  background: blue;
}
<div >i'm a box</div>

  • Related