You can use the method .classList.add('nome da classe')
which will add the class .alterar
to the selected element when the button is clicked. You can place the code inside an attribute onclick
:
onclick="document.querySelector('h1').classList.add('alterar')"
↑__________________________↑ ↑______________________↑
| |
seleciona o elemento adiciona a classe
It is worth noting that the document.querySelector('h1')
will select only the first element h1
what to find. Therefore, if you have more than one <h1>
on the page, you will need to identify it with a specific id for that element by inserting an attribute id
:
<h1 id="h1"> texto qual quer </h1>
↑↑↑↑↑↑↑
And put the id
of the element of document.querySelector
so that the click on the button is directed only to that element:
<input id="botao" onclick="document.querySelector('#h1').classList.add('alterar')" type="button" value="Mudar de cor" />
↑↑↑
Example:
.alterar{
color: red;
text-align: justify;
}
<h1 id="h1"> texto qual quer </h1>
<input id="botao" onclick="document.querySelector('#h1').classList.add('alterar')" type="button" value="Mudar de cor" />
Put what you already have of code there. It is to be only with HTML and CSS or you can use script?
– hugocsl
I put, yes you can use script
– Diogo Serravalle