简体   繁体   中英

How to change CSS style rule within an embedded CSS using JavaScript

So how would I change the CSS styles within embedded CSS with JavaScript only? ex. if this is in the head of the HTML file:

<style>
.middleBTN {
background-color:red;
}
</style>

How would I change it to this within the embedded <style> using JavaScript only?

<style>
.middleBTN {
background-color:blue;
}
</style>

I have an element on a page that does not respond to dynamically changing the color using a JavaScript function. It will however respond to a change from the stylesheet or from the embedded CSS styles.

The usual way would be to add two styles:

<style>
.middleBTNred
{
 background-color:red;
}
.middleBTNblue
{
 background-color:blue;
}
</style>

then change the class of the button with javascript:

document.getElemenyById('myawesomebutton').className='middleBTNblue';

You are trying to change the style of ALL the red buttons so a more appropriate approach would be:

var myawesomebuttons=document.getElemenyByClassName('middleBTNred');
for(var i=0;i<myawesomebuttons.length;i++)
{
 myawesomebuttons[i].className='middleBTNblue';
}

Or the jquery equivalent.

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