18

Possible Duplicate:
jQuery and pseudo-classes

I tried hiding the :after pseudo class via jQuery in a number of ways but with no success, I've found another solution by adding a sort of empty div under my div that contains the :after content and then hiding the div entirely so it gives the same effect.

However I was just curious if anyone had managed to find a way to hide the :after or :before stuff. Here is what I tried that didn't work.

$('.search_box:after').hide();
$('.search_box:after').css('display', 'none');

Just to give you the context, I have a div that contains the search form etc, and when the search is active I want to enable a little arrow indicator under the div pointing like to the list of found items (built with :after via CSS) and when nothing is found, or it defaults to the full out list (since nothing was found) then I want to hide it.

Community
  • 1
  • 1
Andrew Lank
  • 1,607
  • 1
  • 15
  • 29
  • 2
    See here: http://stackoverflow.com/questions/8968992/jquery-and-pseudo-classes – dcpomero Jul 06 '12 at 00:16
  • In the end I just used a div right under my search box, with a height of 0 and same width as search box, and it has the after styling and I hide/unhide it instead of the search box, but TJ VanToll's solution below works also well. – Andrew Lank Jul 07 '12 at 01:44

3 Answers3

56

You cannot do this. Your best bet is to use a class on the element to toggle the display of the pseudo element.

<style>
    .search_box:after {
        content: 'foo';
    }
    .search_box.hidden:after {
        display: none;
    }
</style>
<script>
    //Instead of these 2 lines
    //$('.search_box:after').hide();
    //$('.search_box:after').css('display', 'none');

    //Use
    $('.search_box').addClass('hidden');
</script>

Live example - http://jsfiddle.net/4nbnh/

TJ VanToll
  • 12,584
  • 4
  • 43
  • 45
7

You can dynamically add a <style> block to override it. Give it an id and you can remove it when needed.

Demo: http://jsfiddle.net/ThinkingStiff/TRLY2/

Script:

$( '#hello' ).click( function () {

    if( $( '#pseudo' ).length ) {
        $( '#pseudo' ).remove();
    } else {
        var css = '<style id="pseudo">#hello::after{display: none !important;}</style>';
        document.head.insertAdjacentHTML( 'beforeEnd', css );
    };

} );

​HTML:

<div id="hello">hello</div>​

CSS:

#hello::after {
    content: "goodbye";        
}​
ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
4

ThinkingStiff has a pretty good idea.

You could also add and remove a class to for your search box, and only use the after tag with that.

Something like .hide:after { display:none } and .show:after { /* normal css */ }. Then just swap these classes with javascript.

edit: mixed up the names

dcpomero
  • 979
  • 1
  • 6
  • 17