Home > database >  Remove CSS with JavaScript or jQuery
Remove CSS with JavaScript or jQuery

Time:10-13

I have a style tag in my project, which is generated automatically. I want to remove some of the styles of this tag that interfere with other classes

this is my CSS and style tag:

<style id="style-inline-inline-css">

#et-boc .et-l div {
    text-align: inherit;
    margin: 0;
    padding: 0;
    border: none;
    outline: 0;
    vertical-align: baseline;
    background: transparent;
    letter-spacing: normal;
    color: inherit;
    box-shadow: none;
    -webkit-box-shadow: none;
    -moz-box-shadow: none;
    text-shadow: inherit;
    border-radius: 0;
    -moz-border-radius: 0;
    -webkit-border-radius: 0;
    transition: none;
}

#et-boc .et-l img {
    max-width: 100%;
    height: auto;
}
</style>

I want to remove this two CSS #et-boc .et-l img and #et-boc .et-l div with JavaScript or jQuery and other ways, Due to the structure of the project and the automatic generation of the codes, I cannot delete them on the back-end side. The only way in the front-end is to prevent them from being applied to the site elements

CodePudding user response:

I'm not sure this would be the best approach for your exact goal. Anyway, I took the chance to craft a demo that shows how to access the stylesheets from JavaScript and how to remove a specific CSS rule.

For reference:

This demo shows how a CSS rule can be found and deleted from a given style element (fetched by ID) using its selector as a key:

document.addEventListener('DOMContentLoaded',()=>{
  const styleElement = document.getElementById('style-inline-inline-css');
  const stylesheet = styleElement.sheet;  
  removeCssRuleMatchingSelector(stylesheet, '#et-boc .et-l div');  
});

function removeCssRuleMatchingSelector(stylesheet, selector){
  const cssRules = stylesheet.cssRules;    
  let foundRule = null;
  let foundRuleIndex = -1;
  for(let i=0; i<cssRules.length; i  ){
    if (cssRules[i].selectorText == selector){
      foundRule = cssRules[i];
      foundRuleIndex = i;
      break;
    }      
  }
  if (foundRule !== null){
    stylesheet.deleteRule( foundRuleIndex );    
  }    
}
<style id="style-inline-inline-css">
  
  /*css rule to delete*/
  #et-boc .et-l div {
      background: green;
  }
  
  /*css rule to remain unchanged*/
  .test{
    background: red;
  }
</style>

<div id="et-boc">
  <div >
    <div>If the rule was not deleted, this paragraph would be styled with bg green</div>  
  </div>
</div>

<div >TEST</div>

  • Related