简体   繁体   中英

Jquery delete css class from style section

i have many classes in my style section. How can I remove a class from the styles section using jquery/javascript? For example:

<style id="myStyle"> 
.myClass { color: red);
.myClassSecond { color: black};
</style>

$('.myButton').click(function(){
//delete .myClass from style section
});

The example below will remove a class from any element given. You wouldn't remove the css class from the styles section, you would just remove it from the element for which you do not want to class to be applied.

$(".myButton").click(function(){
    //Replace "elementUsingTheClass" with your element that has the class set
    $("elementUsingTheClass").removeClass("myClass");
});

Although I think it's better to just remove the class from the elements in the page, if you truly want to remove the class from the stylesheet in memory, here's how you get it done (tested in Chrome).

 $('.myButton').click(function(){ //delete .myClass from style section var stylesheets = document.styleSheets; for (var sheet in stylesheets) { var rules = stylesheets[sheet].cssRules; var found = false; for (var rule in rules) { if (rules[rule].selectorText == ".myClass") { found = true; console.log("found"); console.log("deleting rule"); stylesheets[sheet].deleteRule(rules[rule]); } } // verify if (found) { found = false; for (var rule in rules) { if (rules[rule].selectorText == ".myClass") { found = true; console.log("found again :("); } } } console.log(found); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <style id="myStyle"> .myClass { color: black;background-color:red;); .myClassSecond { color: black}; </style> <button class="myClass myButton">Click Me</button> 

You can remove it by reading the text of your style, like

var styleContent = document.getElementById("myStyle").innerText;

and then get the rows, like this:

var sourceRows = styleContent.split("\n");

and then copy the rows you want to keep:

var destinationRows = [];
for (var index in sourceRows) {
    if (sourceRows[index].indexOf(".myClass") < 0)
        destinationRows.push(sourceRows[index]);
} 

and then put it back to your style:

document.getElementById("myStyle").innerText = destinationRows.join("\n");

But beware of the potential problems:

  • you might have styles you want remove outside this style tag
  • you might have rules spanning in multiple rows, in that case this solution will not work per se, but it will be a good starting point

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