Access the css ":after" selector with jQuery

JqueryCssJquery Selectors

Jquery Problem Overview


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'
        }
    )

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

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>');

Solution 3 - Jquery

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondmrView Question on Stackoverflow
Solution 1 - JqueryBlazemongerView Answer on Stackoverflow
Solution 2 - Jqueryr0mankView Answer on Stackoverflow
Solution 3 - JqueryunpezvivoView Answer on Stackoverflow