简体   繁体   中英

javascript - changing a class' style

I've been working with jQuery for a while, but now I want to write something in pure javascript and it's prooving to be challenging.. One of my biggest problems at the moment is that I haven't found a way to set\/change styling for a class. This is not a problem for elements with id, but I want to change the styling for a group of elements with the same class and not just for one element with an id.. In jQuery I would just write:

$('.someClass').css('color','red')

Try the following

var all = document.getElementsByClassName('someClass');
for (var i = 0; i < all.length; i++) {
  all[i].style.color = 'red';
}

Note: As Cheery pointed out getElementsByClassName won't work in IE. The linked question has a nice way to work around this limitation

I find it easier to use CSS variables. You can set the class to use a variable and then change that value in Javascript, thus changing the CSS.

If you style the class like:

:root {
    --some-color: red;
}

.someClass {
    color: var(--some-color);
}

Then you can change the variable's value in Javascript with

document.documentElement.style.setProperty('--some-color', '(random color)');

(random color) can then be anything that would be considered a valid CSS color (eg. blue , black , #626262 , rgb(12, 93, 44) )

Updating the value in JS automatically updates the page as well.

And of course, this can be done with any property, not just color. Here is an example that changes the padding of a class:

CSS

:root {
    --some-padding: 12px;
}

.someClass {
    padding: var(--some-padding);
}

Javascript

// Set padding to 15px
document.documentElement.style.setProperty('--some-color', '15px');

// Set padding to 5rem
document.documentElement.style.setProperty('--some-color', '5rem');

// Set padding to 25%
document.documentElement.style.setProperty('--some-color', '25%');

Sources

How to declare and use CSS variables: https://www.w3schools.com/css/css3_variables.asp
How to update a CSS variable in JS:https://css-tricks.com/updating-a-css-variable-with-javascript/

var sheet = document.createElement('style')
sheet.innerHTML = ".someClass {color: red;}";
document.body.appendChild(sheet);

What you want to change is the style sheet, I guess? Thats possible in Javascript, see

I'm afraid there is no library for that, I really would like to see one...

var all = document.getElementsByClassName('someClass');
for (var i = 0; i < all.length; i++) {
  all[i].className += " red"; 
}

For better coding style add another class to the elements with the code above and then use CSS to change the color of all elements like this:

.red {
  color:red;
}

You can use selector library, for example Sizzle: http://sizzlejs.com/ but if you want pure JS that I guess you are stuck with getting all the elements, and then programatically "handpicking" the ones that have classes you are interested in using RegEx like this for example:

This is an equivalent of your JQuery oneliner:

for( i in document.all) document.all[i].className && /\bpost-text\b/g.test(document.all[i].className) && (document.all[i].style.color = "red")

:)

If you don't need it in one line you can make it faster ( and much more readable ):

var myClassName = "someClass";
var regexp  = RegExp("\\b"+myClassName+"\\b/g");
var elements = document.all;
for( i in elements){
  var this_element = elements[i];
  if(regexp.test(this_element.className){
    this_element.style.color = "red";
  }
}

If " for( i in object) " doesn't work for you, just use classic for loop " for(var i = 0; i < elements.length; i++) ".

It could be ' beautified ' a bit with the use of some slightly more advanced JS concepts ( array function mappings, folding and such ), which JS version are you coding agains? I guess it's not ECMA Script 5, right?

Also, check out this question/answer Get All Elements in an HTML document with a specific CSS Class

You can use:

document.getElementById("MyElement").className = "NewClass";

to change the class of the element and then just define the style for that new class in your CSS file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM