249

I have the following css:

.pageMenu .active::after {
    content: '';
    margin-top: -6px;
    display: inline-block;
    width: 0px;
    height: 0px;
    border-top: 14px solid white;
    border-left: 14px solid transparent;
    border-bottom: 14px solid white;
    position: absolute;
    right: 0;
}

I'd like to change the border-width of the top, left, and bottom border using jQuery. What selector to I use to access this element? I tried the following but it doesn't seem to be working.

$('.pageMenu .active:after').css(
        {
            'border-top-width': '22px',
            'border-left-width': '22px',
            'border-right-width': '22px'
        }
    )
dmr
  • 20,737
  • 36
  • 95
  • 137
  • 2
    Have a look at this answer http://stackoverflow.com/questions/5041494/manipulating-css-pseudo-elements-using-jquery-e-g-before-and-after – BigBadOwl Jul 22 '13 at 13:36
  • 3
    You can't via JQuery, but you can with JavaScirpt (Accessing CSS Rules) http://stackoverflow.com/questions/15087736/change-the-divafter-border-right-color-by-jquery/15088868#15088868 – Ali Bassam Jul 22 '13 at 13:43
  • @AliBassam What you just said makes no sense. jQuery IS Javascript (Actually, a convention library for it, but I hope you get the point). – Kroltan Mar 06 '14 at 14:31
  • 1
    Here's a superb solution with multiple options, including @blazemonger's below: http://stackoverflow.com/questions/5041494/manipulating-css-pseudo-elements-using-jquery-e-g-before-and-after – David Hobs May 30 '14 at 22:49

3 Answers3

326

You can't manipulate :after, because it's not technically part of the DOM and therefore is inaccessible by any JavaScript. But you can add a new class with a new :after specified.

CSS:

.pageMenu .active.changed:after { 
/* this selector is more specific, so it takes precedence over the other :after */
    border-top-width: 22px;
    border-left-width: 22px;
    border-right-width: 22px;
}

JS:

$('.pageMenu .active').toggleClass('changed');

UPDATE: while it's impossible to directly modify the :after content, there are ways to read and/or override it using JavaScript. See "Manipulating CSS pseudo-elements using jQuery (e.g. :before and :after)" for a comprehensive list of techniques.

Community
  • 1
  • 1
Blazemonger
  • 86,267
  • 25
  • 136
  • 177
70

You can add style for :after a like html code.
For example:

var value = 22;
body.append('<style>.wrapper:after{border-top-width: ' + value + 'px;}</style>');
ceving
  • 19,833
  • 10
  • 94
  • 150
r0mank
  • 801
  • 6
  • 4
10

If you use jQuery built-in after() with empty value it will create a dynamic object that will match your :after CSS selector.

$('.active').after().click(function () {
    alert('clickable!');
});

See the jQuery documentation.

Rafa Viotti
  • 9,250
  • 4
  • 39
  • 61
unpezvivo
  • 265
  • 2
  • 2