swap pseudo: after with jquery [duplicate]

2

How can I change the style of a class: after using jquery?

I tried this way but it did not work:

HTML:

<div class="box"></div>

Jquery:

$('.box:after').css({
    borderColor:' #c12 transparent transparent transparent'
});
    
asked by anonymous 04.04.2018 / 23:01

1 answer

2

pseudo-elements ( ::after , ::before etc.) are not in the DOM tree, so they are not accessible via JavaScript.

These elements are only visible on the screen, but are not in the DOM element tree, as stated. If you want to change them, you have to add a specific class.

Example:

$("#b1").click(function(){
   $(".box").addClass("novaclasse");
});

$("#b2").click(function(){
   $(".box").removeClass("novaclasse");
});
.box:after{
   content: 'after';
   border: 10px solid #000;
   border-color: #000 transparent transparent transparent;
}

/* classe que irá alterar o :after */
.box.novaclasse:after{
   border-color: #c12 transparent transparent transparent;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="box">
   principal
</div>
<br>
<input id="b1" type="button" value="Clique para alterar">
<br>
<em>Irá adicionar a classe .novaclasse</em>
<br><br>
<input id="b2" type="button" value="Clique para voltar original">
<br>
<em>Irá remover a classe .novaclasse</em>
    
05.04.2018 / 01:51