3

I have series of buttons with different classes consisting ":before" pseudo elements with different predefined "content" values. Is there is a way to "null" content value of all buttons using javascript (not jquery)?.

.button 1:before{content:"xxx";} .button 2:before{content:"yyy";} .button 3:before{content:"zzz";}...etc.

to

.button 1:before{content:" ";} .button 2:before{content:" ";} .button 3:before{content:" ";}...etc.
Serg
  • 151
  • 10
  • Possible duplicate of [Changing CSS pseudo-element styles via JavaScript](https://stackoverflow.com/questions/4481485/changing-css-pseudo-element-styles-via-javascript) – Heretic Monkey Nov 29 '18 at 22:09

2 Answers2

1

To clear css content property you need to add specific class to elements which will clear that property.

Css:

.clear-content {
   content: none; //you can add !important to make sure you will override other styles
}

Javascript:

document.querySelector(".button_1").classList.add('clear-content');

You can also go through all items for example buttons:

document.querySelectorAll("button").forEach((item) => {
    item.classList.add('clear-content');
});
Łukasz Blaszyński
  • 1,536
  • 1
  • 8
  • 13
  • I missed ":before" in my sample, so it should look like: .button 1:before{content:"xxx";} to .button 1:before{content:" ";}, that's probably why your codes won't work. Sorry for the mess. – Serg Nov 29 '18 at 21:07
0

And here's one-liner trick:

insertRule - Supported by all modern browsers: Codepen

document.styleSheets[0].insertRule('.button:after, .button:before {content: " ";}',0);

addRule - Supported by all modern browsers except FF

document.styleSheets[0].addRule('.button:after, .button:before','content: " ";');
Denys Rusov
  • 560
  • 6
  • 6
  • TypeError: "document.styleSheets[0].addRule is not a function" – Serg Nov 29 '18 at 21:45
  • @Serg - you are right ... I updated my answer: it is preferable to use insertRule because it works in all browsers – Denys Rusov Nov 29 '18 at 22:21
  • "insertRule" doesn't shows an error but does nothing, doesn't overwrite predefined content's value. – Serg Nov 29 '18 at 22:27
  • @Serg - This is strange. Which browser are you using? I created an example on codepen - https://codepen.io/anon/pen/aQPopa . Does it work for you? – Denys Rusov Nov 29 '18 at 22:54
  • "insertRule" with 'content: " "!important; works perfectly. Thank you Denis. – Serg Nov 29 '18 at 23:19
  • @Serg - You welcome. But remember: !important - it's an pure evil :) Thus its desirable to override the styles by weights of selectors - https://www.w3.org/TR/selectors-3/#specificity – Denys Rusov Nov 29 '18 at 23:34