1

Why does this snippet not work on a button? How can I do it correctly?

$('div.button:after').css({
    display:'none'
})
user247702
  • 23,641
  • 15
  • 110
  • 157
user3297073
  • 129
  • 1
  • 12

2 Answers2

5

You cannot select pseudo elements using inline CSS, think like the the way you cannot write :hover styles inline.

What jQuery does with .css() is it injects the styles inline so you cannot change a pseudo element using $('div.button:after').css().


The simple way to achieve that is by using say .addClass() method..

HTML

<div class="button">Hello</div>

CSS

.button:after {
    content: " Hide this using jQuery";
    color: red;
}

.hide_btn_pseudo:after {
    display: none;
}

jQuery

$('div.button').addClass('hide_btn_pseudo');

Demo

Inorder to show the element, you can remove the class back, using .removeClass()

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
1

Actually you can't. Because it is a pseudo-element.

Setting CSS pseudo-class rules from JavaScript

But you can do this instead:

document.styleSheets[0].insertRule("div.button:after { display:'none'; }", 0);
document.styleSheets[0].cssRules[0].style.display= 'none';

Check the link for special IE notes.

Community
  • 1
  • 1
Jorgeblom
  • 3,330
  • 1
  • 23
  • 24