Modify CSS classes using Javascript

前端 未结 3 824
野性不改
野性不改 2020-12-30 00:23

I was wondering if there is an easy way to change the CSS classes in JavaScript. I have gone through all other similar questions here and I couldn\'t find an straight-forwar

3条回答
  •  被撕碎了的回忆
    2020-12-30 00:53

    The reason only one or the other works is because in your second line of code, you destroy the whole style attribute, and recreate it. Note that setAttribute() overwrites the whole attribute.

    A better solution would be to use the element.style property, not the attribute;

    var bg = document.getElementById("myBg");
    bg.style.width = imgWidth + "px";
    bg.style.height = imgHeight + "px";
    

    You can grab all elements with class container and apply it to each of them like this:

    var elements = document.querySelectorAll('.container');
    for(var i=0; i

    Note querySelectorAll isn't supported by IE7 or lower, if you need those then there are shims for getElementsByClassName() here on SO.

提交回复
热议问题