Basj
Basj

Reputation: 46493

Change CSS style of a class with javascript, but not in the DOM

Let's assume we have lots of elements (see Live demo):

<div class="yes">Hello1</div>
<div class="yes">Hello2</div>
<div class="yes">Hello3</div>
<div class="yes">Hello4</div>
<div class="yes">Hello5</div>

with the same class called yes which has a simple CSS style :

.yes { color:red; }

Now I would like to change the style of the yes class.

Of course, we can change CSS style of this class with Javascript by using

var yesarray = document.querySelectorAll('.yes');

for (var i = 0, len = yesarray.length; i < len; i++) {
    yesarray[i].style.color = 'black';
}

(or even more easily with jQuery, with $('.yes').css(...) ...)

But then all these changes will be stored in the DOM :

enter image description here

This is not very elegant if I have lots of elements, that all these styles are "rendered in the DOM" like this.

Question:

How to change CSS style with Javascript such that the style change is not stored in the DOM, but modified in the loaded-in-memory CSS instead?

Upvotes: 1

Views: 4161

Answers (2)

Pointy
Pointy

Reputation: 413737

Instead of modifying every DOM node with class "yes", you can use the power of CSS descendant selectors to make the change a lot cheaper:

CSS:

.yes {
  color: blue; /* or whatever */
}

.approved .yes {
  color: black;
}

Then in JavaScript:

$("body").toggleClass("approved", shouldApprove());

Only one DOM node is updated (though, of course, the browser still has to recompute the layout of the whole page).

Upvotes: 1

MrPk
MrPk

Reputation: 2930

You can't edit the CSS style page, but you can do something else.

You are doing in the right way but with a wrong approach.

You have to add ANTOHER style to each element with "yes" class. This style can be called in your example "approved"

So your jquery call will be:

EDIT: Schmalzy said correctly: $('.yes').addClass('approved');

equivalent of:

 $('.yes').each(){
  $(this).addClass('approved');
}

and previusly you declared in your stylesheet:

.approved {
 color: black
}

So in your page you will store classes (elegant and shorter) and not inline style.

Upvotes: 4

Related Questions