Change content of ::after

Asked

Viewed 60 times

0

I have the following structure:

<div class=duvidas>
   <div>
       <span>Titulo</span>
       <div style='display: none'>Texto</div>
   </div>
</div>

The goal is click on in a span and alter the content of span of '+' for '-'

And make the display of div of none for block.

$('div.duvidas > div').click(function(){
    if ($(this).find ('span').css('display') == 'none') {
      $(this).find ('span::after').attr('data-content','-');
      $(this).find ('div').css('display', 'block');    
    } else {
      $(this).find ('span::after').attr('data-content','+');
      $(this).find ('div').css('display', 'none');    
    }
  })

But it’s not working.

1 answer

2


Pseudo-elements are not accessible via Javascript (see the duplicate). What you can do to change them is by adding a class that changes the ::after in CSS. Now there are problems in your Javascript, where you should check in if if div is visible, not span.

Note in the CSS below that when div has the class .ativo, the content of ::after is amended.

Behold:

$('div.duvidas > div').click(function(){
   if (!$(this).find('div').is(':visible')){ // verifica se a div está visível
      $(this)
      .find('span') // busca o span
      .addClass('ativo') // adiciona a classe
      .end() // volta pro $(this)
      .find('div') // busca a div
      .show(); // mostra a div
   } else {
      $(this)
      .find('span')
      .removeClass('ativo')
      .end()
      .find('div')
      .hide();
   }
})
span::after{
   content: '+';
}

span.ativo::after{
   content: '-';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class=duvidas>
   <div>
       <span>Titulo</span>
       <div style='display: none'>Texto</div>
   </div>
</div>

  • Oh, Sam, thanks worked out. But check it out: There’s not just one div.doubtdiv, there are several. How to do for when to open one, also close the div of the other that is open and stay only 1?

  • Add this before if: $('div.duvidas > div').not(this).find("span").removeClass("ativo").end().find('div').hide();

  • It worked! Thank you very much. Now I’ll take a closer look

  • how it would look if I wanted to put a Transition effect: height 0.8s; at the time of opening and closing?

  • Would have to do in JS because CSS won’t know the height of the element to apply the exact height.

  • ficaria . addClass('active'). css(''Transitions,'height 0.8s')?

  • No, you’d have to use . slideToggle

  • I’ll have to leave now, when I get back I’ll show you an example.

  • good. got here: . slideToggle( "slow" ) thanks!

Show 4 more comments

Browser other questions tagged

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