Is it possible to change text from a "content" of a CSS pseudo element via Javascript?

3

Example below

#test{
    content:"blablabla";
}
    
asked by anonymous 14.12.2017 / 02:13

2 answers

3

The :before and :after rules are not part of DOM and therefore can not be changed using jQuery DOM in>.

But there are ways to manipulate these elements using JavaScript and CSS solutions. One of the ways using jQuery is how @PauloImon replied, you can do with pure JavaScript , see:

let paragrafo = document.querySelector('#paragrafo');
paragrafo.addEventListener('click', (ev) => {
  paragrafo.setAttribute('data-conteudo', 'Novo texto');
});
p:before {
    content: attr(data-conteudo);
}
<p id="paragrafo" data-conteudo="Paragrafo"></p>

You can also add or remove classes, see:

let paragrafo = document.querySelector('#paragrafo');
paragrafo.addEventListener('click', (ev) => {
  paragrafo.classList.toggle('novotexto');
});
p:before {
    content: "Paragrafo";
}
p.novotexto:before {
    content: "Novo texto";
}
<p id="paragrafo"></p>

You can see more example in this answer in SOen .

    
14.12.2017 / 03:12
3

I do not know if it's the best way to do it, but it's an output using jQuery :

$('button').on('click', function () {
  $('div').attr('data-conteudo', 'Mudou!');
});
div::before
{
  content: attr(data-conteudo); /* Recebe o conteúdo do atributo data-conteudo */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divdata-conteudo="Teste"></div>
<br>
<button type="button">Alterar</button>
    
14.12.2017 / 02:27