简体   繁体   中英

change inline class Style property using javascript/jquery

How to change inline class Style property using javascript/jquery. for example:

<style>
.iexp-info-bar-body {
    background-color: #000000;
}
</style>
<div class="iexp-info-bar-body">
//data
</div>

i want to change background-color property of a class .iexp-info-bar-body #000000 to #C04848 .

Please not that i know inline css technique/using !important keyword to change color.
But i want to change all the occurance of a class .iexp-info-bar-body property ie i need a result like

<style>
.iexp-info-bar-body {
    background-color: #C04848;
}
</style>
<div class="iexp-info-bar-body">
//data

I had a very good teacher that taught us to change the class :

  • First, it really helps to be fully aware of "what is my initial state" AND "what is my final state"

This is pretty useful if your design change and you have to implement some transitions. And you will never have to access your JavaScript files to change any css code.

  • Then think about conflicts

Today, you only have one element depending on that class, but what if you have 100 000 tomorrow ?

Maybe try to make another class is the simplest way to achieve what you want to do.

<style>
    .iexp-info-bar-body {
        background-color: #000000;
    }
    .changed {
        background-color: #ff69b4;
    }
</style>

<div class="iexp-info-bar-body">
//data
</div>

<script>
    var all = document.querySelectorAll('.iexp-info-bar-body');
    for (var i = 0, length = all.length; i < length; i++) {
        all[i].classList.remove('iexp-info-bar-body');
        all[i].classList.add('changed');
    }
</script>

Of course this is very primitive and you can improve it in many ways

Have a look at a library called jss . Added or modifying classes is as simple as

jss.set('.demo', {
    'font-size': '15px',
    'color': 'red'
});

This uses the style technique in the header to define the classes similar to the second code block in your question.

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