Henrik Clausen
Henrik Clausen

Reputation: 729

Using javascript to edit class (not inline styles on elements)

I don't thikn that this is possible but I want your input anyway. Lets say that I have a style like this:

<style>
  .something{
    height : 100px;
  }
</style>

and then my HTML looks like this:

<ul>
  <li class="something">1</li>
  <li class="something">2</li>
  <li class="something">3</li>
</ul>

Now I want to change the value "height" in the class ".something", not set new heights of the <li> elements. If i set the style on the elements and then add more <li> elements they will have the original height of the class ".something"


What I want to do is let the user add <li> elements and select height of all the elements. I know I can set them with javascript and just remember to set new <li> elements when they're added, but it would be convenient if I somehow could change:

<style>
  .something{
    height : 100px;
  }
</style>

to e.g.

<style>
  .something{
    height : 85px;
  }
</style>

using javascript

Upvotes: 2

Views: 1130

Answers (1)

Koushik Chatterjee
Koushik Chatterjee

Reputation: 4175

Better place a identity (attribute, id, name) on the style element, so you can target the particular style (DOM) element (will be helpfull when there are many), and then replacethe inner html eg:

<style id="targetStyle">
  .something{
    height : 100px;
  }
</style>

and then in your javascript

var styleDom = document.getElementById('targetStyle');
styleDom.innerHTML = styleDom.innerHTML.replace(/height.*px;/,'height: 85px;');

Build the Regex properly according to your use case, its just a rough example to describe on the part how you can achive this, instead how to replace a string in depth.

Upvotes: 2

Related Questions