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

Asked

Viewed 3,531 times

3

Example below

#test{
    content:"blablabla";
}

2 answers

3

I don’t know if it’s the best way to do it, but it’s an exit 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>

<div data-conteudo="Teste"></div>
<br>
<button type="button">Alterar</button>

3


The rules :before and :after are not part of the GIFT and therefore cannot be changed using the methods GIFT of jQuery.

But there are ways to manipulate these elements using Javascript and or CSS. One of the ways using jQuery is as @Pauloimon replied, you can do with Javascript pure, 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 reply in the Soen.

Browser other questions tagged

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