Change CSS rule definition using jQuery

Suppose you want to change the width of many elements, for example, to simulate a table. I understand you could do this:

$(".class").css('width', '421px');

This changes the inline attribute style='width: 421px;'for each element. Now, what I would like to do is change the actual definition of the CSS rule:

.class {
    width: 375px;  ==[change to]==> 421px;
}

When it comes to 100, if not 1000 nested <ul>and <li>that need to be changed, it seems like it would be better for performance than trying to let jQuery do the work with the method .css().

I found this example - this is what I am trying to do:

var style = $('<style>.class { width: 421px; }</style>')
$('html > head').append(style);

I am NOT trying to swap classes ( $el.removeClass().addClass()) because I cannot have a class for EVERY optimal width (379px, 387px, 402px ..).

<style> , , .

+5
3

document.styleSheets [0].addRule Chrome, FF

+1

What works for me is to include an empty pool in the header:

<style id="custom-styles"></style>

And then manipulate this with something like this:

$('#custom-styles').text('h1 { background: red }')

I tested this, it seems to work in the current version of Chrome (well, Chromium - 63.0) and Firefox (57.0.4).

0
source

All Articles