swap pseudo :after with jquery

Asked

Viewed 1,209 times

2

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

I tried it but it didn’t work:

HTML:

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

Jquery:

$('.box:after').css({
    borderColor:' #c12 transparent transparent transparent'
});
  • Neo, edit your question and include html.

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>
<div class="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>

  • it worked, thank you! https://jsfiddle.net/kdqbz7rt/2/

  • I did not understand, voted to close as duplicate of his own answer and answered again here?

  • Duplicate questions all right, auto-duplicate answers seems odd...

  • If you had a gold medal on the Javascript tag, your vote would close the question immediately. And if I responded and then shut down immediately, it would be improper use of the system.

  • Bueno, the conversation went on a loop. See ya!

  • As a small aside, I also do not agree with giving an answer if you know that it is duplicated and have even voted to close the question as such. The fact that the question is open is a matter of time. The site has the duplicate system precisely to avoid having the same answer spread over thousands of questions. In the end it ends up not adding content and just replicating over and over again with no benefit.

  • I’m sorry, I didn’t understand the duplicate question. but I’m going to uncheck it like the dvd requested...

  • The question I can’t visualize just by talking to create a class....

  • @Thiagolourenço There is no way to enter before through Javascript.

  • @sam, that was my question...so far I haven’t found anything. I just found to change the "content", or else some alternative way.

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.