简体   繁体   中英

Remove CSS rule with !important property

In order to "null" pseudo elements content I use:

  var rule = document.styleSheets[0].insertRule('.video-js * .vjs-icon-placeholder:before {content: " "!important;}', 0);

I works only if ".important" property specified. In some situation I need to restore original pseudo elements content: I tried: document.styleSheets[0].deleteRule(rule) ; That doesn't work. Is there is a way to restore original content?

It doesn't work, because when you remove the rule, it removes the content from the HTML,

I believe the best method would be to get the content first and then reassign.

var prev = window.getComputedStyle(
    document.querySelector('..vjs-icon-placeholder'), ':before'
).getPropertyValue('content')

let prevContent = prev.substring(1,prev.length-1) //to remove the quotes from start and end.

var rule = document.styleSheets[0].insertRule('.video-js * .vjs-icon-placeholder:before {content: " "!important;}', 0);

Now wherever you decide to revert back to previous content.

var rule = document.styleSheets[0].insertRule('.video-js * .vjs-icon-placeholder:before {content: '+prevContent+'!important;}', 0);

Just add another class to the element that sets the content to another value.

 document.querySelector("button").addEventListener("click", function(e){ document.querySelector(".vjs-icon-placeholder").classList.toggle("nocontent"); });
 .vjs-icon-placeholder:before{ content: "This is some before text"; display: block; color: dodgerblue; }.vjs-icon-placeholder.nocontent:before { content: " "; }
 <div class="vjs-icon-placeholder"> This is a div. </div> <button> Toggle Content </button>

If all video-js elements have a common ancestor (you can use the body for this purpose), you can toggle the nocontent class just on that ancestor instead, ie #ancestor.nocontent.video-js *.vjs-icon-placeholder:before{content: " "} and document.querySelector("#ancestor").classList.toggle("nocontent") .

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